define(['moment','module/system/service/WatchDogService'], function (moment) {
    return ['$state','$scope', '$filter', '$stateParams', 'config', 'MMWService', '$mdDialog', '$timeout', 'WatchDogService', 'RouterExtendProvider', '$mddProvider', 
    function ($state,$scope, $filter, $stateParams, config, $MMWService,$mdDialog, $timeout, $WatchDogService, $RouterExtendProvider, $mddProvider) {
        $scope.areaItem = {};     //現在選擇的生產區�?
        $scope.equipmentList = [];//區域內的機台列�?
        $scope.dashboard={};      //儀錶板物件
        $scope.machineItem = {};
        $scope.plot_list=[];//生產批陣列
        $scope.workLogFilterShow = {plot_no: false};
        $scope.step_mode = 0; // 0 關閉掃描流程 | 1 設備 | 2 上工 | 3 下工 | 4 進站 | 5 出站
        $scope.workLogFilter = {plot_no:'', status:''};
        $scope.lineItem = {}; // #0069327 生產線
        //20210604 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
        $scope.select_equipment_no_details = {};
        var nowdatetime = $filter('date')(new Date(), 'yyyy/MM/dd HH:mm:ss');
        //20210628 modify by kaiinagami for M#87684 - 煩請協助更新讓步程式[龍畿]
        //next_op_no參數獨立
        $scope.next_op_no = '';
        //$scope.plotItem = {};
        //20210511 Modify by德義家興for#84772
        $scope.workLogDetail = [];
        $scope.workLogTemp = [];
        // 20230328 add by 文蔚 for M#131657: SMES H5 一體化卡控調整，當子模塊編號OE_EMG為false的時候，需要隱藏今日生產任務的紅字功能
        $scope.OE_EMG = config.cache.module_setting.OE_EMG
        //20230413 add by 翰鴻 for M#132895
        $scope.plot_check_out_counter = 0; //IIoT 出站通知筆數
        $scope.IIoT_Enable = false;
        // 20230303 modify by Alan for#: module_setting卡控
        $scope.ESI_CLD = config.cache.module_setting.ESI_CLD;
        $scope.init = function () {
            //20230413 add by 翰鴻 for M#132895
            if (
                $.grep(config.module, function (n, i) {
                    return n.name == "moduleIIoT"
                }).length > 0
            )
                $scope.IIoT_Enable = true;
            $MMWService.PNIGList = {};
            $scope.areaItem = {
                area_no:''
            };
            $scope.selectButtonAction = {};

            var selectItem = config.selectItem; //取出缓存的产线        
            if (selectItem != null) {
                $scope.areaItem.area_no = selectItem.page_no;
                $scope.areaItem.areaName = selectItem.page_name;
                $scope.areaItem.areadisplay = selectItem.page_no + ' (' + selectItem.page_name + ')';
                $scope.areaItem.WIPEQPCheckMode = selectItem.wipeqpcheckmode;
                $scope.machineItem = {};
                $scope.plotItem = undefined;
                //20210604 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
                $scope.select_equipment_no_details = selectItem;

                //20230413 add by 翰鴻 for M#132895
                if ($scope.IIoT_Enable) {
                    //M#91613 [IIoT] 添加查詢出站通知筆數
                    get_eqp_prod_count($scope.areaItem.area_no, true, function (data) {
                        if (data.page_number_info_get && data.page_number_info_get.length > 0) {
                            $scope.plot_check_out_counter = data.page_number_info_get[0].cnt;
                        }
                    });
                }

                $scope.lineItem = {};
                $scope.mode = 'list';
                lineStatusGet(selectItem);// #0069327 取得產線訊息
                $scope.confirm();
            } else {
                $scope.mode = 'query';
            }
            
            //扣件行業包開啟參數
            $scope.isFastening = (config.cache.sys_parameter['FasteningPackage'] == '1' || config.cache.sys_parameter['FasteningPackage'] == 'Y');
            // 20230314 modify by Alan for#130010: 紧固件行业包卡控顯示雙單位
            $scope._event['production_info_detail.double_unit_qty'].isShown = $scope.isFastening ? 'Y' : 'N';
            $scope.feedingOpionOn = (config.cache.sys_parameter.MaterialFeedingOption == '1');
            $scope.GroupreportworkOption = (config.cache.sys_parameter['UCBModule'] == '1');
            $scope.IsInjectionMolding = (config.cache.sys_parameter.IsInjectionMolding == '1' ||
                                        config.cache.sys_parameter.IsInjectionMolding == 'Y' ||
                                        config.cache.sys_parameter.ISINJECTIONMOLDING == '1' ||
                                        config.cache.sys_parameter.ISINJECTIONMOLDING == 'Y'); // 注塑模組
          
            $mddProvider.UseForm('B0201', (formEntity)=>{
                if(formEntity){
                    $scope.$root.menuList = [];
                    formEntity.funcs.forEach(function(_func){
                        if(_func.funcPosition == 'ToolBar'){
                            let menuItem = {
                                name:_func.name,
                                title:_func.displayText,
                                icon:_func.icon,
                                isShow:_func.isShown != 'N',
                                order:_func.order,
                            };
                            // 20231020 modify by wenwei for M#148194: 厦晖：H5作业区工作平台，报工群组权限问题。
                            if (menuItem.name == 'B0235') menuItem.isShow = $scope.GroupreportworkOption;
                            if (menuItem.name == 'F0101') menuItem.isShow = $scope.feedingOpionOn;
                            if (menuItem.name == 'B0220') menuItem.isShow = !$scope.feedingOpionOn;
                            //20230413 add by 翰鴻 for M#132895
                            if ($scope.IIoT_Enable == false) {
                                if (menuItem.name == "IIoT0101" || menuItem.name == "IIoT0103") {
                                    menuItem.isShow = false;
                                }
                            }
                            if(!config.cache.permissions || config.cache.permissions.indexOf(menuItem.name)!=-1){
                                $scope.$root.menuList.push(menuItem);
                            }
                        }
                    });
                }
            });
            function has_lot_bind(machine_no,callback)
            {
                var content = {};
                content.page_mode = "has_lot_bind_info";
                content.query_condition_info = 
                [{column_name:"EQUIPMENTNO",value:machine_no,query_mode: "0",merge_condition_model: "AND"}];
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                    content : content,
                    success : function(data){
                        if (callback)
                            callback(data);
                    }
                });
            }
            // #0069327 生產線稼動功能
            $scope.changeLine = function () {
                if ($scope.lineItem.machine_status != null && $scope.lineItem.machine_status != '') {
                    // 20240326 modify by Alan for M#160269: 修正傳入的設備狀態來源
                    $scope.lineItem.status = $scope.lineItem.machine_status;
                    $mdDialog.serviceDialog('LineChangeService', $scope.lineItem, function (data) {
                        dog.bark();
                        $scope.lineItem.machine_status = data.machine_status;
                    });
                } else {
                    $scope.$root.showAlert($filter('translate')('LineChange.showAlert.column2'));
                }
            }
            $scope.menuClick = function(item){
                var programName = item.name;
                if (programName == 'B0202') {
                    var machineList = [
                        {machine_no :$scope.areaItem.area_no}
                    ];
                    //上工
                    has_lot_bind($scope.areaItem.area_no,function(data)
                    {
                       if(data.page_number_info_get && data.page_number_info_get.length > 0)
                       {
                           var has_lot = data.page_number_info_get[0].lotbinding;
                           if(has_lot == "1")
                            $mdDialog.serviceDialog('B0250Service', {mode_type:"U",lotInfoList:$scope.dashboard.workLog.production_info_detail,machineList:machineList, type: 'line', parent: 'B0201'}, function(){
                                dog.bark();
                            });
                           else
                           $mdDialog.serviceDialog('B0202Service',
                           {machineList: machineList, type: 'line', parent: 'B0201'}, function(){
                           dog.bark();
                            });
                       }
                    });
                } else if (programName == 'B0203') {
                    var machineList = [
                        {machine_no :$scope.areaItem.area_no}
                    ];
                    //下工
                    has_lot_bind($scope.areaItem.area_no,function(data)
                    {
                       if(data.page_number_info_get && data.page_number_info_get.length > 0)
                       {
                           var has_lot = data.page_number_info_get[0].lotbinding;
                           if(has_lot == "1")
                            $mdDialog.serviceDialog('B0250Service', {mode_type:"D",lotInfoList:$scope.dashboard.workLog.production_info_detail,machineList:machineList, type: 'line', parent: 'B0201'}, function(){
                                dog.bark();
                            });
                           else
                           $mdDialog.serviceDialog('B0203Service', machineList, undefined, 'line', function(){
                                dog.bark();
                            });
                       }
                    });
                } else if (programName == 'B0220') {
                    $scope.$root.getService('B0220Service', function($B0220Service){
                        $B0220Service.trenching($scope.areaItem.area_no, function(){
                            dog.bark();
                        });
                    });
                } else if (programName == 'B0227') {
                    //全數下工
                    has_lot_bind($scope.areaItem.area_no,function(data)
                    {
                       if(data.page_number_info_get && data.page_number_info_get.length > 0)
                       {
                           var has_lot = data.page_number_info_get[0].lotbinding;
                           if(has_lot == "1")
                           $scope.$root.getService('B0250Service', function($B0250Service){
                                $B0250Service.employee_wrok_set_json({
                                    machine_list : [{machine_no:$scope.areaItem.area_no}],
                                },function(){
                                    dog.bark();
                                });
                            });
                           else
                           $scope.$root.getService('B0203Service', function($B0203Service){
                            $B0203Service.employee_wrok_set_json({
                                machine_list : [{machine_no:$scope.areaItem.area_no}],
                                callback:function(){
                                    dog.bark();
                                }
                            });
                            });
                       }
                    });
                } else if (programName == 'B0221') {
                    var machine_type = '';
                    for(var i = 0; i <  $scope.equipmentList.length; i++){
                        if($scope.equipmentList[i].machine_no == $scope.areaItem.area_no){
                            machine_type =  $scope.equipmentList[i].machine_type;
                            break;
                        }
                    }
                    //20221012 add by 翰鴻 for M#118366
                    var proList = new Set();
                    $.each($scope.dashboard.workLog.production_info_detail, function (index, obj) {
                        if (obj.status == 'R' || obj.status == 'Q' || obj.status == 'W')
                            proList.add(obj.item_no);
                    });
                    $mdDialog.serviceDialog('B0221Service',{
                        parent: "B0201",
                        machine : {
                            machine_no: $scope.areaItem.area_no,
                            machine_type: machine_type
                        },
                        ProductList: Array.from(proList),
                        callback : function(){
                            dog.bark();
                        }
                    });
                } else if (programName == 'B0211') {
                    if($scope.machineItem.machine_display != null && $scope.machineItem.machine_display != ''){
                        $scope.machineItem.status = $scope.machineItem.status;
                        $mdDialog.serviceDialog('B0211PageService',$scope.machineItem, function(){
                            dog.bark();
                        });
                    }else{
                        $scope.$root.showAlert($filter('translate')('B0201.showAlert.column7'));
                    }
                } else if (programName == 'LineChange') {// #0069327 新增"生產線稼動"
                    $scope.changeLine();
                } else if (programName == 'F0101') {
                    //物料管理
                    $mdDialog.serviceDialog('F0101Service',{
                        parent: 'B0201',
                        wo_no: $scope.plotItem.wo_no,
                        op_no: $scope.plotItem.op_no,
                        lot_no: $scope.plotItem.plot_no,//20210507 modify by 德義_林佳諺 for #0086310 檢查PlugIn需要之參數
                        machine_no: $scope.areaItem.area_no,
                        check_dispatch_machine: $scope.machineItem.dispatch_mode,  // 20231103 modify by Alan for#0149409 : 是否為派工設備
                        callback : function(){
                            dog.bark();
                        }
                    });
                } else if (programName == 'B0235') { //群组报工
                    //M#82424 修正報工群組在產線無法開啟(須帶入產線編號 而非設備) by a991241234
                    //20220206 modify by wangzy forM#0111287: 修正生产线点击报工群组上工，再点开报工群组无上工人员信息和比例，作业区有
                    var tempEquipmentList = [{ machine_no: $scope.areaItem.area_no, employee_work_detail: $scope.dashboard.workOperator.work_member_detail}];
                    /*$scope.equipmentList.forEach(function (equipment) {
                        if ($scope.dashboard.machineStatusPlus.machineStatus[equipment.machine_no].isSelect) {
                            tempEquipmentList.push(equipment);
                }
                    });
                    if (tempEquipmentList.length == 0) {
                        tempEquipmentList.push($scope.machineItem);
                    }*/

                    $mdDialog.serviceDialog('B0235Service', tempEquipmentList, 'machine', 'B0201', function () {
                        dog.bark();
                    });
                }
                else if (programName == 'CUS001') {
                    if ($scope.dashboard.workLog.production_info_detail.length > 0) {
                        $mdDialog.serviceDialog('CUS001Service',   
                            $scope.machineItem,
                            $scope.areaItem,
                            $scope.plotItem,
                            function () { dog.bark(); });
                    }
                    else {
                        $scope.$root.showAlert($filter('translate')('B0215C.msg.noLotData'));
                    }
                }

                //20230413 add by 翰鴻 for M#132895
                else if (programName == 'IIoT0101') {
                    $mdDialog.serviceDialog('IIoT0101_Service', {
                        parent: 'B0201',
                        equipment_no: $scope.areaItem.area_no,
                        feedback: function (dialog) {
                            dialog.hide();
                            dog.bark();
                        }
                    });
                }
                else if (programName == 'IIoT0103') {
                    var options = {};
                    options.area_no = $scope.areaItem.area_no;
                    options.equipment_no = $scope.areaItem.area_no;
                    options.parent = "B0201";
                    options.feedback = function (dialog) {
                        dog.bark();
                        dialog.hide();
                    }
                    $mdDialog.serviceDialog('IIoT0103_Service', options);
                }

            };
            $scope.$root.getService('B0222Service', function($B0222Service){
                $B0222Service.init($scope)
            });

            /**Slight**/
            $scope.slight_details = $RouterExtendProvider.slight_details;
        };

        $scope.back = function(){
            if($scope.mode == 'query'){
                $scope.$root.changeProgram('home', true);
            } else {
                $scope.disconnection = false;
                $scope.final(function(){
                    $scope.equipmentList = [];
                    $scope.machineItem = {};
                    $scope.mode = 'query';
                });
            }
        };

        //20230413 add by 翰鴻 for M#132895
        //M#91613 [IIoT] 添加查詢出站通知筆數
        function get_eqp_prod_count(machine_no, isShowLoading, callback) {
            var content = {};
            content.page_mode = "3T_EQP_PROD_COUNT";
            content.query_condition_info =
                [{ column_name: "EQUIPMENTNO", value: machine_no, query_mode: "0", merge_condition_model: "AND" }];
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                content: content,
                success: function (data) {
                    if (callback)
                        callback(data);
                }
            }, isShowLoading);
        }
        $scope.final = function(callback){
            if(refresh_timer != undefined){
                $timeout.cancel(refresh_timer);
                refresh_timer = undefined;
            }
            if(count_info_dog != undefined){
                $timeout.cancel(count_info_dog);
                count_info_dog = undefined;
            }
            $WatchDogService.stopWatch();
            if(typeof callback === 'function')
                callback();
        }

        $scope.barcodeScan = function(event){
            if(event.keyCode == 13){
                $scope.search();
            }
        };

        // 20220624 modify by Alan for#100246 : 安灯生产线工作平台页面重制
        $scope.confirm = function(){
            //設定單頭
            if($scope.areaItem.area_no != ''){
                $scope.workLogStatus = 'Q';
                $scope.dashboard = {
                    workLog : {
                        mode: 'B0201',
                        templateUrl: 'module/moduleB/program/B02/B0201/B0201_WorkLog.html',
                        statusList : ['Q', 'R', 'W', 'C', 'O', 'I']
                    },
                    productInfo: {
                        templateUrl: 'module/moduleB/program/B02/B0201/B0201_ProductInfo.html',
                    },
                    workMaterialOp: {
                        templateUrl : 'module/moduleB/program/dashboard/workMaterialOp.html'
                    },
                    workOperator: {
                        mode : 'B0201',
                        templateUrl: 'module/moduleB/program/dashboard/workOperator.html'
                    },
                    workMaterial: {
                        templateUrl : 'module/moduleB/program/dashboard/workMaterial.html'
                    },
                    machineStatus: {
                        templateUrl: 'module/moduleB/program/B02/B0201/B0201_MachineStatus.html',
                        machineList: $scope.equipmentList
                    },
                    accessory : {
                        templateUrl : 'module/moduleB/program/dashboard/accessory.html'
                    },
                    dashboard_info : {
                        templateUrl : 'module/moduleB/program/dashboard/dashboard_info.html',
                        isContentHide:true,
                        isForceHide:false,
                        rate_detail:[]
                    },
                    slightModuleInfo: { // 安燈按鈕模塊
                        templateUrl: '',
                    }
                };
                
                // 20230224 modify by Alan for#: module_setting卡控
                if($scope.ESI_CLD) {
                    $scope.dashboard.countInfo = {
                        templateUrl : 'module/moduleB/program/dashboard/countInfo.html'
                    }
                }

                $scope.slightModule = config.cache.sys_parameter["SlightModule"]; // 安燈模組權限
                if ($scope.slightModule && $scope.slightModule === '1') {
                    // 有啟動安燈模組時，operatorInfo 模塊的畫面排版方式需要調整
                    // $scope.dashboard.operatorInfo.templateUrl = 'module/moduleMSG/program/dashboard/operatorInfo.html';
                    $scope.dashboard.slightModuleInfo.templateUrl = 'module/moduleMSG/program/dashboard/slightModuleInfo.html';
                    $scope.slightModuleCss = 'slightModuleCss';
                    $scope.dashboardPanel.push('slightModuleInfo');
                }

                if (typeof(Storage) !== 'undefined') {
                    var panel_setting = JSON.parse(localStorage.getItem(config.appName + '_B0201_panel'));
                    if(panel_setting){
                        // 20230303 modify by Alan for#: module_setting卡控
                        // 檢查保存在local stroage的設定，有權限才套用
                        var pass = true;
                        if(pass && panel_setting.includes('workMaterialOp')){
                            pass = $scope.feedingOpionOn;
                        }
                        if(pass && panel_setting.includes('countInfo')){
                            pass = $scope.ESI_CLD;
                        }
                        if(pass) {
                            $scope.dashboardPanel = panel_setting;
                        }
                    }   
                }
                $scope.PageConfig = {
                    page : 0,
                    page_count : 25
                };
                $scope.workLogOrder = {}; //生產任務排序物件
                //取出機台列表
                production_machine_info_get($scope.areaItem.area_no, function(){
                    $WatchDogService.startWatch(dog, true);
                }, true);

                //取得集成資訊
                count_info_get(function(feedback, isShowLoading){
                    count_info_dog = $timeout(function(){
                        count_info_get(feedback, false);
                    }, 1000);
                }, true);
            } else {
                $scope.$root.showAlert($filter('translate')('B0201.msg.selectLine'));
            }

        };

        //選擇生產區�?
        $scope.loadAreaList = function() {
            $scope.$root.showQueryList({
                title:$filter('translate')('B0201.msg.selectLine'),
                header: [
                    {label:$filter('translate')('B0201.queryList.column1'), code:'page_no'},
                    {label:$filter('translate')('B0201.queryList.column2'), code:'page_name'}
                ],
                query: function(conditions, feedback){
                    var use_favourite = false;
                    if(config.setting.OperatingArea && config.setting.OperatingArea!=''){
                        use_favourite = true;
                        conditions.push({column_name:'B.MASTERTYPE', query_mode:'0', value:'3', merge_condition_model:'AND' });
                        conditions.push({column_name:'B.MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                    } else {
                        conditions.push({column_name:'B.MASTERTYPE', query_mode:'0', value:'-1', merge_condition_model:'AND' });
                    }
                    $MMWService.pageNumberInfoGet({
                        page_mode: '0-1',
                        query_condition_info:conditions
                    }, function(itemList){
                        var temp = itemList;
                        if(use_favourite){
                            temp = $filter('filter')(temp, {favourite:'1'});
                        }
                        if(temp && temp.length){
                            feedback(temp);
                        } else {
                            $scope.$root.showConfirm($filter('translate')('B0201.msg.favorite_empty'), function(confirmDialog){
                                confirmDialog.hide();
                                $timeout(function(){
                                    $scope.favorite(function(){
                                        $scope.loadAreaList();
                                    });
                                }, 200);
                            });
                        }
                    });
                },
                selectCode:$scope.areaItem.area_no,
                confirm : function(selectItem,dialog){
                    $scope.areaItem.area_no = selectItem.page_no;
                    $scope.areaItem.areaName = selectItem.page_name;
                    $scope.areaItem.areadisplay = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    $scope.areaItem.WIPEQPCheckMode = selectItem.wipeqpcheckmode;
                    $scope.machineItem = {};
                    $scope.plotItem = undefined;
                    //20210604 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
                    $scope.select_equipment_no_details = selectItem;

                    $scope.lineItem = {};                    
                    lineStatusGet(selectItem);// #0069327 取得產線訊息

                    //20230413 add by 翰鴻 for M#132895
                    if ($scope.IIoT_Enable) {
                        //M#91613 [IIoT] 添加查詢出站通知筆數
                        get_eqp_prod_count($scope.areaItem.area_no, true, function (data) {
                            if (data.page_number_info_get && data.page_number_info_get.length > 0) {
                                $scope.plot_check_out_counter = data.page_number_info_get[0].cnt;
                            }
                        });
                    }
                    dialog.hide();
                    $scope.confirm();
                    config.selectItem = selectItem; //将选择的产线进行缓存
                }
                
            });
        };
        //#0069327 取得產線狀態
        function lineStatusGet(selectItem) {
            var content = { machine_no: selectItem.page_no };
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_EQP.machine_status_info_get',
                content: content,
                success: function (data) {
                    if (data.machine_status_get_detail.length != 0) {
                        $scope.lineItem.machine_no = data.machine_status_get_detail[0].machine_no;
                        $scope.lineItem.machine_name = data.machine_status_get_detail[0].machine_name;
                        $scope.lineItem.machine_display = selectItem.page_no + ' (' + selectItem.page_name + ')';
                        $scope.lineItem.machine_status = data.machine_status_get_detail[0].status;
                    } else {
                        $scope.lineItem.machine_no = selectItem.page_no;
                        $scope.lineItem.machine_name = selectItem.page_name;
                        $scope.lineItem.machine_display = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    }
                }
            });
        }

        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
        var refresh_timer;
        function ErrorHandler(msg, isShowLoading, callback){
            if($scope){
                $scope.$root.showAlert(msg);
                if(!isShowLoading){
                    $scope.disconnection = true;
                    $scope.refresh =  function(){
                        $scope.disconnection = false;
                        $timeout.cancel(refresh_timer);
                        refresh_timer = undefined;
                        callback();
                    };
                    if(refresh_timer == undefined){
                        refresh_timer = $timeout(function(){
                            $scope.refresh();
                        }, config.setting.RefreshTime*1000);
                    }
                }
            }
        }

        // 是否允許進出站報�?
        function isAllowReport(){
            var is_allow_report = true;
            if($scope.areaItem.WIPEQPCheckMode == '2'){ // 1:報工設備狀態不檢查 2: 報工設備狀態檢�?
                var machine_list = $filter('filter')($scope.equipmentList, {is_virtual: 'N'}, true);
                if(machine_list.length > 0){
                    for (var i = 0; i < machine_list.length; i++){
                        //設備狀態不在待機、生產中，則不允許報�?
                        if(machine_list[i].status != '0' && machine_list[i].status != '1'){
                            is_allow_report = false;
                            break;
                        }
                    }
                }
            }
            return is_allow_report;
        }
        
        // 20220624 modify by Alan for#100246 : 安灯生产线工作平台页面重制
        //生產機台資訊取得
        function production_machine_info_get(area_no, feedback, isShowLoading) {
            var content = {
                area_no:area_no,
                query_mode:'01'
            };

            //20180604 modify by 李栋 for mantis#0047537
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.production_machine_info_get',
                content : content,
                success : function(data){
                        let lastMachine = {};
                        let machineList = [];
                        // 20230713 modify by shiwl for#0139805 : 优化设备信息闪现问题
                        $scope.lineItem.child_machine_no = data.machine_detail[0].machine_no;// #0069327 取得產線下設備編號  
                        $scope.isAllowReport = isAllowReport();
                        lastMachine = $scope.machineItem;
                        machineList = data.machine_detail;
                        $scope.machineItem = getCurrentMachine(lastMachine, machineList);
                        $scope.dashboard.machineStatus.machineList = $filter('filter')(data.machine_detail, { is_virtual: 'N' }, true);
                        $scope.equipmentList = data.machine_detail; // 20240410 modify by Alan for#161408 : 不要過濾虛擬設備，上下具會用到
                        machine_working_info_get('1111', feedback, isShowLoading);
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        production_machine_info_get(area_no, feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        production_machine_info_get(area_no, feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        // 20220624 modify by Alan for#100246 : 取得當前設備
        const getCurrentMachine = (lastMachine, machineList) => {
            const isMachineListEmpty = machineList.length < 0;
            const isLastMachineEmpty = isEmpty(lastMachine);
            const noLastMachine = machineList.filter((machine) => machine.machine_no === lastMachine.machine_no).length <= 0;
            if(isMachineListEmpty) {
                return {};
            } else if(isLastMachineEmpty && noLastMachine) {
                return machineList[0];
            } else {
                return lastMachine;
            }
        }

        // 20220624 modify by Alan for#100246 : 安灯生产线工作平台页面重制
        //設備加工資訊取得
        function machine_working_info_get(data_type, feedback, isShowLoading)  {

            //  20231012 modify by shiwl for#0147594: 【正式区】生产线平台的生产线状态变更后没有实时更新
            lineStatusGet($scope.select_equipment_no_details);// #0069327 取得產線訊息
            var content = {
                machine_no: $scope.areaItem.area_no,
                work_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                data_type : data_type
            };
   
            //20180518 modify by 李栋 for mantis#0046663
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_EQP.machine_working_info_get',
                content : content,
                success: function (data) {
                    
                    if (angular.fromJson(localStorage[config.appName + "_B0201_workLogStatusList"])) {
                        $scope.dashboard['workLog'].statusList = [];
                        angular.fromJson(localStorage[config.appName + "_B0201_workLogStatusList"]).forEach(function(temp) {
                            $scope.dashboard['workLog'].statusList.push(temp);
                        });
                    };
                    $scope.dashboard.workOperator.work_member_detail = data.machine_member_work_detail;  //上工人員列表
                    $scope.dashboard.workLog.production_info_detail = data.machine_production_info_detail; //今日生產任務
                    //20210607 modify by 德義林佳諺 for M#0069327: 若有R生產批, 則將產線狀態更改為加工
                    //20210624 modify by 德義林佳諺 for M#0069327: 為能正常更改產線狀態, 取消此作用
                    //changeLineFirst();
                    // 20210828 modify by chenshibo for#98846：改为从后端取，前端没必要在forEach了
                    ////20210511 Modify by德義家興for#84772
                    //$scope.dashboard.workLog.production_info_detail.forEach(function(item){
                    //    if(item.status == 'C'){
                    //        //getPlotV_CONTS(item,content.machine_no);//取得每日生產任務;當日同一生產批出站的次數
                    //        // 20210828 modify by chenshibo for#98846：频繁调用后端服务有很大效能问题，已经取出来直接计算就好，没必要再去数据库查询
                    //        var templist = $scope.dashboard.workLog.production_info_detail.filter(function (plotItem) {
                    //            return plotItem.op_no == item.op_no && plotItem.plot_no == item.plot_no && plotItem.status == 'C';
                    //        });
                    //        item.v_conts = templist.length;
                    //    }
                    //})
                    getWorkLogPlotDetail(content.machine_no);//取得每日生產任務;已出站生產批的資訊
                    //$scope.dashboard.productInfo = angular.merge($scope.dashboard.productInfo, data.machine_production_history_info_detail[0]);    //生產資訊
                    $scope.dashboard.workMaterial.materials_detail = data.machine_materials_detail;  //上料資訊
                    $scope.dashboard.workOperator.CategoryLeader = data.CategoryLeader;
                    
                    andon_eqp_status_info_get(); // 取得安燈按鈕
                    //設備集成
                    /*
                    $scope.dashboard.dashboard_info.update_time = data.param_update_time;
                    $scope.dashboard.dashboard_info.counter = data.current_count;
                    $scope.dashboard.dashboard_info.rate_detail = data.machine_param_detail;
                    */
                    // 20231123 modify by wenwei for M#137875: iiot 计数器 
                    let all_param_type_equal_N =  data.machine_param_detail.every(item => item.param_type == 'N')
                    // 20190701 modify by Dustdusk for M#: 不會每次都跳出來
                    if(!$scope.dashboard.dashboard_info.isForceHide){
                        // 20230303 modify by Alan for#: module_setting卡控
                        if(data.machine_param_detail.length > 0 && $scope.ESI_CLD && !all_param_type_equal_N){
                            $scope.dashboard.dashboard_info.isContentHide = false;
                        } else {
                            $scope.dashboard.dashboard_info.isContentHide = true;
                        }
                    }
                    //smt bool 生產線判�?
                    $scope.dashboard.dashboard_info.is_smt = data.is_smt;
                    //上方班別資訊
                    $scope.shift_begin = data.shift_begin;
                    $scope.shift_end = data.shift_end;
                    if(data.shift_desc.length>0){
                        $scope.shift_desc = data.shift_desc.substring(0,1);
                    } else {
                        $scope.shift_desc = '';
                    }
                    try{
                        $scope.mode = 'list';
                        //$scope.$root.loadMenu();
                        machine_accessory_map_get(feedback, isShowLoading);
                    }catch(e){
                        console.error(e);
                    }
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        machine_working_info_get(data_type, feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        machine_working_info_get(data_type, feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }
	
        // 20220624 add by Alan for#100246 : 安灯生产线工作平台页面重制
        // 取得安燈按鈕
        function andon_eqp_status_info_get() {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_MSG.andon_eqp_status_info_get',
                content: {
                    equipment_no: $scope.machineItem.machine_no
                },
                success: function (data) {
                    if (data.andon_data && data.andon_data.length > 0) {
                        $scope.andon_min_time = data.andon_min_time || ''; // 安燈時間
                        $scope.andon_data = data.andon_data; // 安燈按鈕資訊
                    }
                }
            });
        }
        
        // 取得安燈按鈕顏色
        // 20220729 modify by Alan for#100246 : 配合現有樣式調整安燈面板預設顏色
        $scope.getSlightColor = function (item) {
            // 後台回傳色碼為 N/A 時，要自行判斷，剩下可以在車間調色盤設定，直接由後台帶回來
            if (item.slight_colour === 'N/A') {
                if (item.slight_status === '4') { // 4: 藍色
                    return { background: '#1ab7cd' };
                } else if (item.slight_status === '1' || item.slight_status === '2' || item.slight_status === '3') { // 1、2、3: 紅色
                    return { background: '#DD4264' };
                } else { // 0 : 綠色
                    return { background: '#91D472' }; // 預設綠色
                }
            } else {
                return { background: item.slight_colour }; // 後台直接帶色碼回來
            }
        }

        // 執行點擊的安燈按鈕 -> 請搭配 SA 規格查看
        $scope.slightBtn = function (item) {
            if (item.slight_status === '0') {
                if (!item.write_info) { // 0
                    onePointOneSlight(item); // 安燈邏輯 1.1
                } else { // 1
                    onePointTwoSlight(item); // 安燈邏輯 1.2
                }
            } else if (item.slight_status === '1') {
                if (!item.receive_project) { // 0
                    if (!item.write_start) { // 0
                        fiveSlight(item); // 安燈邏輯 5
                    } else { // 1
                        fourSlight(item); // 安燈邏輯 4
                    }
                } else { // 1
                    twoSlight(item); // 安燈邏輯 2
                }
            } else if (item.slight_status === '2') {
                threeSlight(item); // 安燈邏輯 3
            } else if (item.slight_status === '3') {
                fiveSlight(item); // 安燈邏輯 5
            } else if (item.slight_status === '4') {
                sevenSlight(item); // 安燈邏輯 7
            } else {
                // 查無此安燈邏輯，請重新確認
                $scope.$root.showAlert($filter('translate')('B0214.slightMsg.column3'));
            }
        }
	
        //20210607 add by 德義林佳諺 for M#0069327: 若有R生產批, 則將產線狀態更改為加工
        function changeLineFirst() {
            if ($scope.lineItem.machine_status && $scope.lineItem.machine_status != '0') {
                var status_r = false;
                $scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                    if (item.status && item.status == 'R')
                        status_r = true;
                });
                if (status_r) {
                    var content = {};
                    var plan_work = {
                        date: nowdatetime.split(' ')[0],
                        time: nowdatetime.split(' ')[1]
                    };
                    var status = $scope.lineItem.machine_status;
                    var work_time = $filter('date')(plan_work.date, 'yyyy/MM/dd') + " " + plan_work.time;
                    content = {
                        machine_no: $scope.areaItem.area_no,
                        report_datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                        machine_status: '0',
                        remark: '',
                        handle_user_no: config.cache.account,
                        plan_start_time: status == '0' || status == '1' ? '' : work_time,
                        actual_end_time: status == '0' || status == '1' ? work_time : '',
                        remarks: undefined
                    };
                    changeMachineStatusProcess(content);
                }
            }
        }

        // 20220729 delete by Alan for#100246 : 移除重複的程式碼

        //模製具資訊取�?
        function machine_accessory_map_get(feedback, isShowLoading){
            var content = {
                machine_no: $scope.areaItem.area_no,
                is_line : '1'
            };

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_ACC.machine_accessory_map_get',
                content : content,
                success : function(data){
                    $scope.dashboard.accessory.accessory_detail = data.accessory_detail;
                    try{
                        //$scope.$root.loadMenu();
                        checkLotInfo(feedback, isShowLoading);
                        //if(feedback)
                        //    feedback();
                    }catch(e){
                        console.error(e);
                    }
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        machine_accessory_map_get(feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        machine_accessory_map_get(feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        // 20220624 add by Alan for#100246 : 安灯生产线工作平台页面重制
        // 安燈邏輯 1.1
        function onePointOneSlight(item) {
            var content = {
                slight_status: item.slight_status, // 安燈狀態
                write_info: item.write_info, // 是否側錄安燈訊息選項 -> 0 : 否 ; 1 : 是
                write_start: item.write_start, // 是否處理安燈任務開始時間選項 -> 0 : 否 ; 1 : 是
                receive_project: item.receive_project, // 是否必須接受安燈任務選項 -> 0 : 否 ; 1 : 是
                //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                change_eqp_status: item.change_eqp_status, //安灯时是否同步改变设备状态  0 = 否 1 = 是
                eqp_status: item.eqp_status, //0-7对应安灯后设备将要修改成的状态        
                eqp_status_back: item.eqp_status_back, //0-否 1-是 安灯处理流程结束后是否自动将设备状态还原至安灯前
                eqp_status_list: [ // 每個安燈邏輯帶入的資料都不同
                    {
                        equipment_no: $scope.machineItem.machine_no,
                        slight_type_no: item.slight_type_no
                    }
                ]
            };

            // 安燈寫入
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_MSG.andon_eqp_status_process',
                content: content,
                success: function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                    //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                    dog.bark(); // 刷新設備資訊
                }
            });
        }

        // 安燈邏輯 1.2
        function onePointTwoSlight(item) {
            $mdDialog.serviceDialog(
                'Andon00Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                    //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                    dog.bark(); // 刷新設備資訊
                }
            );
        }

        // 安燈邏輯 2
        function twoSlight(item) {
            if (item.slight_status === '2' && item.receiver) {
                let newItem = angular.copy(item);
                $MMWService.pageNumberInfoGet({
                    page_mode: 'andon_eqp_status_get',
                    query_condition_info: [
                        { column_name: 'SLightTypeNo', query_mode: '0', value: item.slight_type_no, merge_condition_model: 'AND' },
                        { column_name: 'EquipmentNo', query_mode: '0', value: $scope.machineItem.machine_no, merge_condition_model: 'AND' }
                    ]
                }, function (itemList) {
                    if (itemList && itemList.length > 0) {
                        newItem.slight_status = itemList[0].slightstate;
                        newItem.receiver = itemList[0].receiver;
                        threeSlight(newItem);
                    } else {
                        // 查無安燈狀態
                        $scope.$root.showAlert($filter('translate')('B0214.slightMsg.column2'));
                    }
                });
            } else {
                // 該安燈任務需要相應人員接受後才可以繼續後續流程
                $scope.$root.showAlert($filter('translate')('B0214.slightMsg.column1'));
            }
        }

        // 安燈邏輯 3
        function threeSlight(item) {
            if (!item.write_start) { // 0
                fiveSlight(item); // 安燈邏輯 5
            } else { // 1
                fourSlight(item); // 安燈邏輯 4
            }
        }

        // 安燈邏輯 4
        function fourSlight(item) {
            $mdDialog.serviceDialog(
                'Andon02Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                }
            );
        }

        // 安燈邏輯 5
        function fiveSlight(item) {
            $mdDialog.serviceDialog(
                'Andon01Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                }
            );
        }

        // 安燈邏輯 7
        function sevenSlight(item) {
            $mdDialog.serviceDialog(
                'Andon03Service',
                item,
                $scope.machineItem.machine_no,
                function () {
                    andon_eqp_status_info_get(); // 刷新安燈按鈕
                    //20210423 Modify by德義家興for#78800: [标准][安灯/讯息][DEV]安灯与设备稼动联动机制
                    dog.bark(); // 刷新設備資訊
                }
            );
        }

        /*取得設備集成資訊*/
        var count_info_dog;
        function count_info_get(feedback, isShowLoading)  {
            if(($scope.areaItem != undefined && $scope.dashboardPanel.includes('countInfo'))
                    || (!$scope.dashboard.dashboard_info.isForceHide && !$scope.dashboard.dashboard_info.isContentHide)){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_EQP.machine_working_info_get',
                    content : {
                        machine_no: $scope.areaItem.area_no,
                        data_type : '0000'
                    },
                    success : function(data){
                        //設備集成
                        //20201223 3.2.2.DEV.2020122301 M#0079362:[標準][本土][IIOT] [DEV]計數器顯示增列上次出站數量
                        if (data.param_update_time !== null && data.param_update_time != undefined) {  //出站紀錄
                            $scope.dashboard.dashboard_info.update_time = moment(data.param_update_time).format('YYYY-MM-DD HH:mm');
                        } else {
                            $scope.dashboard.dashboard_info.update_time = "";
                        }
                        if (parseInt(data.current_count) > 0) { //當前計數量
                            $scope.dashboard.dashboard_info.current_count = parseInt(data.current_count);
                        } else {
                            $scope.dashboard.dashboard_info.current_count = 0;
                        }
                        if (data.counter_pre != "" && data.counter_pre !== null && data.counter_pre != undefined) { //前次出站計數量
                            $scope.dashboard.dashboard_info.counter_pre = parseInt(data.counter_pre);
                        } else {
                            $scope.dashboard.dashboard_info.counter_pre = 0;
                        }
                        if (data.counter != "" && data.counter !== null && data.counter != undefined) { //計數總量
                            $scope.dashboard.dashboard_info.counter = parseInt(data.counter);
                        } else {
                            $scope.dashboard.dashboard_info.counter = 0;
                        }
                        $scope.dashboard.dashboard_info.rate_detail = data.machine_param_detail;
                        //20230413 add by 翰鴻 for M#132895
                        if ($scope.IIoT_Enable) {
                            //IIoT M#91511 計數器上生產批資料
                            $scope.dashboard.dashboard_info.machine_no = $scope.areaItem.area_no;
                            $scope.dashboard.dashboard_info.counter_equipment = [];
                            if (data.counter_equipment) {
                                data.counter_equipment.forEach(function (c_item) {
                                    var obj = {};
                                    obj.item_title = c_item.lot_no + "：";
                                    obj.item_content = Math.round(c_item.accQty) + "/" + Math.round(c_item.lot_total_qty);
                                    $scope.dashboard.dashboard_info.counter_equipment.push(obj);
                                });
                            }
                            //IIoT M#91613  添加查詢出站通知筆數
                            if ($scope.areaItem && $scope.areaItem.area_no) {
                                get_eqp_prod_count($scope.areaItem.area_no, false, function (data) {
                                    if (data.page_number_info_get && data.page_number_info_get.length > 0) {
                                        $scope.plot_check_out_counter = data.page_number_info_get[0].cnt;
                                    }
                                })
                            }
                        }
                        // 20231123 modify by wenwei for M#137875: iiot 计数器 
                        let all_param_type_equal_N =  $scope.dashboard.dashboard_info.rate_detail.every(item => item.param_type == 'N')
                        // 20190701 modify by Dustdusk for M#: 不會每次都跳出來
                        if(!$scope.dashboard.dashboard_info.isForceHide){
                            if($scope.dashboard.dashboard_info.rate_detail.length > 0 && !all_param_type_equal_N){
                                $scope.dashboard.dashboard_info.isContentHide = false;
                            } else {
                                $scope.dashboard.dashboard_info.isContentHide = true;
                            }
                        }
                        try{
                            feedback(feedback, isShowLoading);
                        }catch(e){console.log(e);}
                    },
                    error: function(data){
                        //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                        console.error(data.Message);
                        feedback(feedback, isShowLoading);
                    },
                    netError: function(msg){
                        //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                        console.error(msg);
                        feedback(feedback, isShowLoading);
                    }
                }, isShowLoading);
            } else {
                feedback(feedback, isShowLoading);
            }
        }

        function checkLotInfo(callback, isShowLoading){
            if($scope.dashboard.workLog.production_info_detail.length > 0){
                if(!$scope.plotItem){
                    $scope.plotItem = $scope.dashboard.workLog.production_info_detail[0];
                }
                lotinfo_get($scope.plotItem, callback, isShowLoading);
            } else {
                $scope.dashboard.productInfo.item_code = '';
                $scope.dashboard.productInfo.product_name = ''; // 20230503 add by Alan for M#: 產品名稱未清空
                $scope.dashboard.productInfo.wo_no = '';
                $scope.dashboard.productInfo.plot_no = '';
                $scope.dashboard.productInfo.qty = '';
                $scope.dashboard.productInfo.OutputQty = '';
                $scope.dashboard.productInfo.ScrapQty = '';
                $scope.dashboard.productInfo.GoodQty = '';
                $scope.dashboard.productInfo.DESCRIPTION = '';
                $scope.dashboard.productInfo.reached_rate = '';
                $scope.dashboard.productInfo.next_op_no = '';
                $scope.dashboard.productInfo.flow_chart_url = '';
                if(callback)
                    callback();
            }
        }

        var reload_time = 0;
        function lotinfo_get(plotItem, callback, isShowLoading){
            var content = {
                LotNo : plotItem.plot_no,
                OPNo : plotItem.op_no,
                Status: plotItem.status,
                machine_no: $scope.areaItem.area_no
            };
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.plot_display_info_get',
                content : content,
                success : function(data){
                    reload_time = 0; //清除取得紀�?
                    $scope.dashboard.productInfo.item_code = data.ProductNo;
                    $scope.dashboard.productInfo.wo_no = data.MONo;
                    $scope.dashboard.productInfo.plot_no = data.LotNo;
                    $scope.dashboard.productInfo.product_name = data.ProductName;//產品名稱
                    $scope.dashboard.productInfo.qty = data.CurQTY;
                    $scope.dashboard.productInfo.OutputQty = data.OutputQty;
                    $scope.dashboard.productInfo.ScrapQty = data.ScrapQty;
                    $scope.dashboard.productInfo.GoodQty = data.GoodQty;
                    $scope.dashboard.productInfo.DESCRIPTION = data.DESCRIPTION;
                    $scope.dashboard.productInfo.reached_rate = data.TodayArriveRate + '%';
                    //20210611 modify by kaiinagami for M#87684 - $scope.plotItem增加next_op_no, 使B0209可以判斷末站
                    $scope.dashboard.productInfo.next_op_no = data.next_op_no;
                    //20210628 modify by kaiinagami for M#87684 - 煩請協助更新讓步程式[龍畿]
                    //next_op_no參數獨立
                    $scope.next_op_no = data.next_op_no;
                     //20230322 modify by ShengKun for M# 121894: 序列號檢驗優化
                     $scope.dashboard.productInfo.NeedSN = data.NeedSN;

                    var online_rate;
                    if(!data.AreaUserNum || data.AreaUserNum == 0){
                        data.AreaUserNum = $scope.dashboard.workOperator.work_member_detail.length;
                        online_rate = 100;
                        $scope.dashboard.workOperator.light_type = '';
                    } else {
                        online_rate = Math.floor(($scope.dashboard.workOperator.work_member_detail.length / data.AreaUserNum)*100);
                        if($scope.dashboard.workOperator.work_member_detail.length == (+data.AreaUserNum)){
                            $scope.dashboard.workOperator.light_type = 'green';
                        } else {
                            $scope.dashboard.workOperator.light_type = 'red';
                        }
                    }
                    $scope.dashboard.workOperator.title_info = $scope.dashboard.workOperator.work_member_detail.length + '/' + data.AreaUserNum + ' ' +online_rate+ '%';
                    $scope.dashboard.productInfo.next_op_no = data.next_op_no;
                    $scope.dashboard.productInfo.flow_chart_url = data.flow_chart_url;
                    if(callback)
                        callback();
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    if(isShowLoading == false){
                        reload_time++;
                        if(reload_time<2){
                            $scope.plotItem = undefined;
                            checkLotInfo(callback, isShowLoading);
                        } else {
                            //$scope.$root.showAlert(data.Message, function(){
                            $scope.plotItem = undefined;
                            if(callback)
                                callback();
                            //});
                        }
                    } else {
                        $scope.$root.showAlert(data.Message);
                    }
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一�?
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        lotinfo_get(plotItem, callback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        var dog = {
            bark:function(feed, next){
                //使用user.infomation.get取得使用者資�?
                // 20220127 modify by chenshibo for#107097：画面关闭后，刷新没有进度，可以直接点击刷新前数据做其它操作
                //20230413 edit by 翰鴻 for M#132895
                if (!$scope.IIoT_Enable)
                    production_machine_info_get($scope.areaItem.area_no, next, true);
                else
                    production_machine_info_get($scope.areaItem.area_no, next, false);
            }
        };

/****SLight**************************************************/
        $scope.showSlight = function(){
            return $RouterExtendProvider.showSlight();
        }

        $scope.showSlightList = function(slight_type_no){
            //$scope.$root.loadSideSubMenu(undefined, {mode:'mailbox'});
            $RouterExtendProvider.showMailList(slight_type_no);
        }

/****DialogList*************************************************************************************************************************************/
        //Status 說明 :
        // 來自 Plot :  Q, R, C, W
        // 來自機台 : M
        // 來自Barcode/QRcode : B
        function first_check_defect_qty(qc_type, callback) {
            var content = {
                machine_no: $scope.areaItem.area_no,
                op_no: $scope.plotItem.op_no,
                plot_no: $scope.plotItem.plot_no,
                qc_type: qc_type
            }
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.first_check_defect_qty',
                content: content,
                success: function (data) {
                    callback(data);
                }
            });
        }

        // 20231206 add by Alan for M#151347: 返回生產任務是否被選中
        $scope.checkSelect = function (item) {
            if ($scope.plotItem) {
                return ($scope.plotItem.plot_no == item.plot_no)
                    && ($scope.plotItem.op_no == item.op_no)
                    && ($scope.plotItem.status == item.status);
            } else {
                return false;
            }
        };

        $scope._event = {
            'machineList': {
                rowClick: (item, args) => {
                    $scope.machineItem = item;
                    andon_eqp_status_info_get(); // 取得安燈按鈕
                    //$scope.openToolBar('M');
                    item.machine_status = 'M';
                    $scope._event['production_info_detail'].openBubbleList(item, args);
                }
            },
            'work_member_detail': {
                rowClick: (item, args) => {
                    if (!config.cache.permissions || config.cache.permissions.indexOf('B0203') != -1) {
                        var machineList = [
                            { machine_no: $scope.areaItem.area_no }
                        ];
                        $mdDialog.serviceDialog('B0203Service', machineList, item, 'line', function () {
                            dog.bark();
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('common.msg.no_permissions'));
                    }
                }
            },
            'production_info_detail': {
                // 20231031 modify by Alan for M#148965: 增加預設值，避免報錯
                getPages: (list, PageConfig, filterItem = {}, orderItem) => {
                    if (list) {
                         // 20231121 modify by shiwl    0150629: 【乔登卫浴】作业区平台产品编号等栏位有设置上下标，但是不能排序
                        if(orderItem)
                        list =  $filter('orderBy')(list,orderItem.code,orderItem.order);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            //狀態過��?
                            if (isOK && $scope.dashboard['workLog'].statusList.indexOf(item.status) == -1) {
                                isOK = false;
                            }
                            return isOK;
                        });
                        var orderCondition = genHeadOrderCondition(orderItem || {});
                        if (orderCondition && orderCondition.length > 0)
                            temp_list = $filter('orderBy')(temp_list, orderCondition);
                        if (PageConfig) {
                            PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count) || 1;
                            if (PageConfig.page >= PageConfig.total_page) {
                                PageConfig.page = 0;
                            }
                            var index = PageConfig.page * PageConfig.page_count;
                            $scope.temp_list = temp_list;
                            $scope.plot_list = temp_list.slice(index, index + PageConfig.page_count)
                            return temp_list.slice(index, index + PageConfig.page_count);
                        } else {
                            $scope.temp_list = temp_list;
                            $scope.plot_list = temp_list;
                            return temp_list;
                        }
                    } else {
                        $scope.temp_list = list;
                        $scope.plot_list = list;
                        return list;
                    }
                },
                rowClick: (item, args) => {
                  //  $scope.flag = item.starting_check_status;
                  $scope.flag ="B0229";
                    $scope.plotItem = item;
                    // 20210330 modify by 奕達 for M#90257
                    lotinfo_get(item, undefined, true);
                    $scope.workLogStatus = item.status;
                    var content = {
                        op_no: $scope.plotItem.op_no
                    };
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_MAT.check_plugIn',
                        content: content,
                        success: function (data) {
                            if (parseInt(data.qty, 10) >= 1) {
                                $scope.isPlugInEqualFive = true;
                            } else {
                                $scope.isPlugInEqualFive = false;
                            }
                        }
                    });
                    $scope.plotItem.open_scan_column = false; //把進出站的掃描欄位關掉
                    $scope._event['production_info_detail'].openBubbleList(item, args);
                },
                checkSelect: (item) => $scope.checkSelect(item)
            },
            'production_info_detail.double_unit_qty': {
                isShown: 'N'
            }
        }

        $scope._fn = {
            'production_info_detail.F0101': { //物料管理
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'C', 'W', 'P'].includes(item.status)
                        && $scope.feedingOpionOn
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'F0101Service', {
                        parent: 'B0201',
                        wo_no: $scope.plotItem.wo_no,
                        op_no: $scope.plotItem.op_no,
                        lot_no: $scope.plotItem.plot_no,//20210507 modify by 德義_林佳諺 for #0086310 檢查PlugIn需要之參數
                        machine_no: $scope.areaItem.area_no,
                        check_dispatch_machine: $scope.machineItem.dispatch_mode,  // 20231103 modify by Alan for#0149409 : 是否為派工設備
                        callback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0228': { //始业点检
                // 20230325 modify by Alan for#0130601 : 修正 始业点检關窗後的狀態
                // 20230322 modify by Alan for#0130601 : 修正 始业点检顯示
                //20210507 modify by shiwl for #0130601 starting_check_status为1 始业点检异常不显示始业点检按钮
                isShown: (item, args) => {
                    return (
                        ['Q'].includes(item.status)
                        && item.starting_check_status != '1'
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0228Service', {
                        areaNo: $scope.areaItem.area_no,
                        plotItem: $scope.plotItem,
                        feedback: function () {
                          lineStatusGet( $scope.select_equipment_no_details);// #0069327 取得產線訊息;
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0229': { 
                // 20230325 modify by Alan for#0130601 : 修正 始业点检關窗後的狀態
                // 20230322 modify by Alan for#0130601 : 修正 始业点检异常解除 顯示
                isShown: (item, args) => {
                    return (
                        ['Q'].includes(item.status)
                        && item.starting_check_status === '1'
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0228Service', {
                        type: 'release',
                        areaNo: $scope.areaItem.area_no,
                        plotItem: $scope.plotItem,
                        feedback: function () {
                        lineStatusGet( $scope.select_equipment_no_details);// #0069327 取得產線訊息;
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0204': {//上料
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                        && !$scope.feedingOpionOn
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0204Service', $scope.areaItem, $scope.plotItem, 'line', function () {
                        dog.bark();
                    });
                }
            },
            'production_info_detail.Inject02': {//Recipe參數
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                        && $scope.IsInjectionMolding
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'Inject02Service', $scope.machineItem, $scope.plotItem);
                }
            },
            'production_info_detail.B0230': {//標籤列印
                isShown: (item, args) => ['Q', 'R', 'W', 'C'].includes(item.status) ? 'Y' : 'N',
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0230Service', { plotItem: $scope.plotItem });
                }
            },
            'production_info_detail.B0205': {//進站報工
                isShown: (item, args) => {
                    return (
                        ['Q', 'B'].includes(args.stauts || item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    // 20231109 modify by Alan for#0150018: 出站报工界面和输入的生产批号不一样
                    $scope.plotItem = item;
                    // 20170511 modify by Dustdusk for 調整進站報工的方�?
                    if (item.status == 'Q') {
                      
                           $mdDialog.serviceDialog(args.func.funcForm || 'B0205Service', $scope.areaItem, $scope.plotItem, 'line', function (content) {
                                   // 因machine_status_info_get內容: 前端"加工": 0 , 後端"加工": 1
                                   if ($scope.lineItem.machine_status && $scope.lineItem.machine_status != 0) {
                                       changeMachineStatusProcess(content);
                                   }
                                   dog.bark();
                          });
                      
                      
                    } else if (item.status == 'B') {//TODO 刷條碼
                        var plotInfo = angular.merge({}, $scope.plotItem);
                        $scope.$root.getService(args.func.funcForm || 'B0205Service', function ($B0205Service) {
                            $B0205Service.SMES_PlotCheckInProcess({
                                machine_no: $scope.areaItem.area_no,
                                plotInfo: plotInfo,
                                type: 'line',
                                feedback: function () {
                                    dog.bark();
                                }
                            });
                        });
                    }
                }
            },
            // 工艺点检
            'production_info_detail.CUS001': {
                isShown: (item, args) => {
                    return (['0', '1'].includes($scope.lineItem.machine_status)) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $scope.plotItem = item;
                    $mdDialog.serviceDialog(
                        args.func.funcForm || 'CUS001Service',
                        $scope.machineItem,
                        $scope.areaItem,
                        $scope.plotItem,
                        function () { dog.bark(); });
                }
            },
            'production_info_detail.B0206': {//出站報工
                isShown: (item, args) => {
                    return (
                        ['R', 'B'].includes(args.stauts || item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    // 20231109 modify by Alan for#0150018: 出站报工界面和输入的生产批号不一样
                    $scope.plotItem = item;
                    var msg = '';
                    //20190506 modify by Dustdusk for M#56727: 根據AllowCheckOutWithOutOperator判斷出站是否需要有人在線上
                    //20211125 modify by Liuyang for M#99947:改为Y或1时检核
                    if (config.cache.sys_parameter.AllowCheckOutWithOutOperator == 'Y' || config.cache.sys_parameter.AllowCheckOutWithOutOperator == '1') {
                        if ($scope.dashboard['workOperator'].work_member_detail == undefined
                            || $scope.dashboard['workOperator'].work_member_detail.length == 0) {
                            msg = $filter('translate')('B0201.msg.no_online_operator');
                        }
                    }
                    if (msg == '') {
                        //20221012 add by 翰鴻 for M#118366
                        var proList = new Set();
                        $.each($scope.dashboard.workLog.production_info_detail, function (index, obj) {
                            if (obj.status == 'R' || obj.status == 'Q' || obj.status == 'W')
                                proList.add(obj.item_no);
                        });
                        $mdDialog.serviceDialog(args.func.funcForm || 'B0206Service', $scope.areaItem, $scope.plotItem, 'line', 'B0201', function (content) {
                            // 因machine_status_info_get內容: 前端"閒置": 1 , 後端"閒置": 0
                            //20210605 modify by 德義林佳諺 for M#0069327 判斷是否改產線為閒置
                            // 20230809 modify by wenwei for M#142120 在重新抓取生產任務之後才更改產線狀態
                            dog.bark(undefined, function () {
                                var count = 0;
                                $scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                                    if (item.status == 'R') {
                                        count++;
                                    }
                                });
                                if (count == 0) {//是否為最後一筆'R'
                                    changeMachineStatusProcess(content);
                                }
                            });
                        }, proList);
                    } else {
                        $scope.$root.showAlert(msg);
                    }
                }
            },
            'production_info_detail.B0234': {//工單模治具
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                        && $scope.IsInjectionMolding
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0234Service', {
                        plotItem: $scope.plotItem,
                        feedback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0218': {//批次進站
                isShown: (item, args) => {
                    return (
                        ['Q'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    // 20200713 modify by WeiTing for M#74348: 把過濾後的狀態Q的生產批帶到批次進站裡做判斷。
                    $scope.temp_list = $scope.temp_list.filter(function (plotItem) {
                        return plotItem.status === 'Q';
                    });
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0218Service', $scope.plotItem, $scope.areaItem.area_no, $scope.workLogFilter.plot_no, 'B0201', $scope.temp_list, function (content) {
                        // 20231110 modify by wenwei for M#149719: 6009[ORACLE][在线][生产任务中心]生产线工作平台生产批批量进站后，生产线状态为闲置
                        // 20231215 modify by wenwei for M#153129: [H5][生产任务中心]生产线工作平台-批量进站后提示信息有误
                        // 因machine_status_info_get內容: 前端"加工": 0 , 後端"加工": 1
                        if ($scope.lineItem.machine_status && $scope.lineItem.machine_status != 0) {
                            changeMachineStatusProcess(content);
                        }
                        dog.bark();
                    });
                }
            },
            'production_info_detail.B0219': {//批次出站
                isShown: (item, args) => {
                    return (
                        ['R'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    var msg = '';
                    //20190506 modify by Dustdusk for M#56727: 根據AllowCheckOutWithOutOperator判斷出站是否需要有人在線上
                    //20211125 modify by Liuyang for M#99947:改为Y或1时检核
                    if (config.cache.sys_parameter.AllowCheckOutWithOutOperator == 'Y' || config.cache.sys_parameter.AllowCheckOutWithOutOperator == '1') {
                        if ($scope.dashboard['workOperator'].work_member_detail == undefined
                            || $scope.dashboard['workOperator'].work_member_detail.length == 0) {
                            msg = $filter('translate')('B0201.msg.no_online_operator');
                        }
                    }
                    if (msg == '') {
                        // 20210427 modify by 14169 for M#91283: 把過濾後的狀態R的生產批帶到批次出站裡做判斷。
                        $scope.temp_list = $scope.temp_list.filter(function (plotItem) {
                            return plotItem.status === 'R';
                        });
                        $mdDialog.serviceDialog(args.func.funcForm || 'B0219Service', $scope.plotItem, $scope.areaItem.area_no, $scope.workLogFilter.plot_no, 'B0201', $scope.temp_list, function () {
                            dog.bark();
                        });
                    } else {
                        $scope.$root.showAlert(msg);
                    }
                }
            },
            'production_info_detail.B0207-1': {//首件檢查
                isShown: (item, args) => {
                    return (
                        ['R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0207Service', {
                        parent: 'B0201',
                        plotItem: $scope.plotItem,
                        machine_no: '',
                        area_no: $scope.areaItem.area_no,
                        type: '0',
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號。
                        product_id: $scope.dashboard.productInfo.item_code,
                        feedback: function () {
                            dog.bark();
                        },
                        needsn: $scope.dashboard.productInfo.NeedSN,
                    });
                }
            },
            'production_info_detail.B0207-2': {//巡檢
                isShown: (item, args) => {
                    return (
                        ['R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                }, click: (item, args) => {
                    first_check_defect_qty(3, function (param) {
                        var input_qty = param.input_qty;
                        var defect_qty = param.defect_qty;
                        if (input_qty > defect_qty) {
                            // 20230322 modify by alan for#130771: 巡檢type字段應為'2'
                            $mdDialog.serviceDialog(args.func.funcForm || 'B0207Service', {
                                parent: 'B0201',
                                plotItem: $scope.plotItem,
                                machine_no: '',
                                area_no: $scope.areaItem.area_no,
                                type: '1',
                                // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號。
                                product_id: $scope.dashboard.productInfo.item_code,
                                queryNumber: param,
                                feedback: function () {
                                    dog.bark();
                                },
                                needsn: $scope.dashboard.productInfo.NeedSN,
                            });
                        } else {
                            $scope.$root.showAlert($filter('translate')('B0214.msg.all_current_production_batches_are_inspected_as_defective_and_cannot_be_inspected_again'));
                        }
                    });
                }
            },
            'production_info_detail.B0240': {//自检
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    // 20230322 modify by alan for#130771: 自检type字段應為'5'
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0240Service', {
                        parent: 'B0201',
                        plotItem: $scope.plotItem,
                        machine_no: '',
                        area_no: $scope.areaItem.area_no,
                        type: '3',
                        // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號。
                        product_id: $scope.dashboard.productInfo.item_code,
                        feedback: function () {
                            dog.bark();
                        },
                        needsn: $scope.dashboard.productInfo.NeedSN,
                    });
                }
            },
            'production_info_detail.B0241': {//末检
                isShown: (item, args) => {
                    return (
                        ['R', 'C'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    first_check_defect_qty(4, function (param) {
                        // 20221130 modify by shiwl for M#122742 - 针对巡检、末检，如果已验不良数量（未出站）>=R状态数量，则不允许执行检验
                        var input_qty = param.input_qty;
                        var defect_qty = param.defect_qty;
                        if (input_qty > defect_qty) {
                            // 20230322 modify by alan for#130771: 末检type字段應為'4'
                            $mdDialog.serviceDialog(args.func.funcForm || 'B0241Service', {
                                parent: 'B0201',
                                plotItem: $scope.plotItem,
                                machine_no: '',
                                area_no: $scope.areaItem.area_no,
                                type: '2',
                                // 20200110 modify by WeiTing for M#66287 - SPC檢驗須要多傳入品號。
                                product_id: $scope.dashboard.productInfo.item_code,
                                queryNumber: param,
                                feedback: function () {
                                    dog.bark();
                                },
                                needsn: $scope.dashboard.productInfo.NeedSN
                            });
                        } else {
                            $scope.$root.showAlert($filter('translate')('B0214.msg.all_current_production_batches_are_inspected_as_defective_and_cannot_be_inspected_again'));
                        }
                    });
                }
            },
            'production_info_detail.B0208': {//暫停
                isShown: (item, args) => {
                    if ('Q' == item.status && ['0', '1'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else if ('R' == item.status) {
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0208Service', {
                        machine_no: $scope.areaItem.area_no,
                        plotItem: $scope.plotItem,
                        feedback: function (content) {
                            // 20240507 modify by wenwei for M#162440: [6.0.1PATCH][MSSQL][H5][解除暂停]生产线工作平台重工报错
                            dog.bark(undefined, function () {
                                let countR = 0;
                                const filteredR = $scope.dashboard.workLog.production_info_detail.some(item => {
                                    if (item.status === 'R') {
                                        countR++;
                                        if (countR > 1) return true;
                                    }
                                    return false;
                                });
                                if (countR == 0) {//是否為最後一筆'R'
                                    //20240511 modify by wenlei for M#162444
                                    // machine_status == '0' 只有原设备状态=加工时，当前设备无加工中任务才需切换设备状态为闲置
                                    if($scope.lineItem.machine_status == '0'){
                                        changeMachineStatusProcess(content);
                                   } 
                                }
                            });
                        }
                    });
                }
            },
            'production_info_detail.B0209': {//解除暫停
                isShown: (item, args) => ['W'].includes(item.status) ? 'Y' : 'N',
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0209Service', {
                        machine_no: $scope.areaItem.area_no,
                        plotItem: $scope.plotItem,
                        //20210628 modify by kaiinagami for M#87684 - 煩請協助更新讓步程式[龍畿]
                        //next_op_no參數獨立
                        next_op_no: $scope.next_op_no,
                        // 20240507 modify by wenwei for M#162440: [6.0.1PATCH][MSSQL][H5][解除暂停]生产线工作平台重工报错
                        feedback: function (content) {
                            dog.bark(undefined, function () {
                                var count = 0;
                                $scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                                    if (item.status == 'R') {
                                        count++;
                                    }
                                });
                                if (count > 0) {//当前设备有R状态任务
                                    //20240511 modify by wenlei for M#162444
                                    // machine_status == '1' 只有原设备状态=闲置时，当前设备有加工中任务才需切换设备状态为加工
                                    if($scope.lineItem.machine_status == '1'){
                                        changeMachineStatusProcess(content);
                                   } 
                                }
                            });
                        },
                        employeeStatus: $scope.dashboard['workOperator'].work_member_detail
                    });
                }
            },
            'production_info_detail.B0212': {//ESOP
                isShown: (item, args) => ['Q', 'R', 'C', 'W', 'P'].includes(item.status) ? 'Y' : 'N',
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0212Service', $scope.plotItem);
                }
            },
            'production_info_detail.A0401': {//分批作業
                isShown: (item, args) => {
                    if ('Q' == item.status && ['0', '1'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else if ('R' == item.status) {
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'A0401Service', {
                        plotItem: $scope.plotItem,
                        feedback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.A0402': {//併批作業
                isShown: (item, args) => {
                    if ('Q' == item.status && ['0', '1'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else if ('R' == item.status) {
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'A0402Service', {
                        plotItem: $scope.plotItem,
                        feedback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0213': {//重工
                isShown: (item, args) => {
                    if ('Q' == item.status && ['0', '1'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else if ('R' == item.status && ['0', '1', '3', '6', '7'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0213Service', {
                        machine_no: $scope.areaItem.area_no,
                        plot_detail: [$scope.plotItem],
                        feedback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0223': {//產品變更
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'W', 'C'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                        && $scope.plotItem.product_change == '2'
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0223Service', {
                        plotItem: $scope.plotItem,
                        feedback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0226': {//設備變更
                isShown: (item, args) => {
                    if ('W' == item.status && ['0', '1'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else if ('R' == item.status) {
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click: (item, args) => {
                    //20220822 modify by 翰鴻 for M#105814
                    var switch_plot_state;
                    if ($scope.workLogStatus == 'W')
                        switch_plot_state = 2;
                    else
                        switch_plot_state = 1;

                    $mdDialog.serviceDialog(args.func.funcForm || 'B0226Service', {
                        type: 'line',
                        machine_no: $scope.areaItem.area_no,
                        plotItem: $scope.plotItem,
                        switch_plot_state: switch_plot_state,
                        callback: function () {
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0210': {//設備點檢
                isShown: (item, args) => {
                    return (
                        ['M'].includes(item.machine_status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {  	// 20240104 modify by shiwl for M# 0155368: 【江阴标榜】【正式区+测试区】执行设备点检点击确定后报错
                    selectedEquipmentList = [];
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0210Service', $scope.machineItem,selectedEquipmentList,function () {
                        dog.bark();
                    });
                }
            },
            'production_info_detail.B022501': {//報工還原
                isShown: (item, args) => {
                    if ('Q' == item.status && ['0', '1'].includes($scope.lineItem.machine_status)) {
                        return 'Y';
                    } else if ('R' == item.status) {
                        return 'Y';
                    } else {
                        return 'N';
                    }
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0225Service', {
                        machine_no: $scope.areaItem.area_no,
                        machine_status: $scope.lineItem.machine_status,
                        plotItem: $scope.plotItem,
                        callback: function (dataChange) {
                            // #69327 報工還原依照需求稼動產線狀態
                            if (dataChange.machine_status && dataChange.machine_status == 'R') {
                                if ($scope.lineItem.machine_status != '1') {// #69327 後端"閒置"代號為"1"
                                    //20210605 modify by 德義林佳諺 for M#0069327 判斷是否改產線為閒置
                                    var count = 0;
                                    $scope.dashboard.workLog.production_info_detail.forEach(function (item) {
                                        if (item.status == 'R') {
                                            count++;
                                        }
                                    });
                                    if (count == 1) {//是否為最後一筆'R'
                                        dataChange.machine_status = '1';// #69327 後端"閒置"代號為"0"
                                        changeMachineStatusProcess(dataChange);
                                    }
                                }
                            }
                            if (dataChange.machine_status && dataChange.machine_status == 'Q') {
                                //20210604 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
                                if ($scope.lineItem.machine_status != '0') {// #69327 前端"加工"代號為"0"
                                    //20210604 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
                                    dataChange.machine_status = '0';// #69327 後端"加工"代號為"1"
                                    changeMachineStatusProcess(dataChange);
                                }
                            }
                            dog.bark();
                        }
                    });
                }
            },
            'production_info_detail.B0211': {//稼動變更
                isShown: (item, args) => {
                    return (
                        ['M'].includes(item.machine_status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $mdDialog.serviceDialog(args.func.funcForm || 'B0211Service', $scope.machineItem, function () {
                        dog.bark();
                    });
                }
            },
            'production_info_detail.G0101': {//子作業
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'C', 'W'].includes(item.status)
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    $scope.$root.changeProgram(args.func.funcForm || 'G0101', {
                        data: {
                            plot_no: $scope.plotItem.plot_no,
                            op_no: $scope.plotItem.op_no,
                            op_name: $scope.plotItem.op_name
                        }
                    });
                }
            }, //20230815 modify by shiwl 0142184: [MSSQL][6.0][在线][工艺插件-热处理]工艺特性信息收集按钮未显示
            'production_info_detail.B0237': {//工藝特性資訊收集
                isShown: (item, args) => {
                    return (
                        ['Q', 'R', 'W'].includes(item.status)
                        && ['0', '1'].includes($scope.lineItem.machine_status)
                        && $scope.plotItem.op_plug_in == 1
                    ) ? 'Y' : 'N';
                },
                click: (item, args) => {
                    var heat_plot_no = '',
                        op_plug_in_detail = $scope.plotItem.op_plug_in_detail;

                    // 判斷是否有爐批號
                    if (op_plug_in_detail && op_plug_in_detail.length > 0) {
                        if (op_plug_in_detail[0].heat_plot_no && op_plug_in_detail[0].heat_plot_no !== '') {
                            heat_plot_no = op_plug_in_detail[0].heat_plot_no;
                        }
                    }

                    $mdDialog.serviceDialog(args.func.funcForm || 'B0237Service', {
                        machine_no: $scope.areaItem.area_no,
                        machine_name: $scope.areaItem.areaName,
                        heat_plot_no: heat_plot_no,
                        plot_no: $scope.plotItem.plot_no,
                        op_no: $scope.plotItem.op_no,
                        callback: function () {
                            dog.bark();
                        }
                    });
                }
            }
        }

        $scope.loadSmtLineState = function(item)
        {
            $MMWService.sendToServer({
                uri : 'ServicesSMT.Module_SMT.smt_on_work_detect_process',
                content : 
                {
                    area_no:$scope.areaItem.area_no,
                    lot_no:item.plot_no
                },
                success : function(data)
                {
                  item.smt_line_state = data.work_state;
                }
            });
        }
        function open_smt_login_check()
        {
            $mdDialog.dialog('module/moduleB/program/B02/B0201/SmtLoginCheck.html',smtLoginController);
        }
        function smtLoginController(dialog)
        {
            var controller = {
                area_no:"",
                account:"",
                password:"",
                init:function()
				{
                    dialog.area_no = $scope.areaItem.area_no;
                },
                back: function () 
				{
					dialog.hide();
                },
                confirm: function () 
				{
                    if(dialog.account.trim().length > 0 && dialog.password.trim().length > 0)
                    {
                        $MMWService.sendToServer({
                            uri : 'ServicesSMT.Module_SMT.login_area_check_process',
                            content : 
                            {
                                area_no:dialog.area_no,
                                account:dialog.account,
                                password:dialog.password
                            },
                            success : function(data)
                            {
                              if(data.check_res)
                              {
                                dialog.hide();
                                if($scope.selectButtonAction.init)
                                    $scope.selectButtonAction.init($scope.workLogStatus);
                              }
                            }
                        });
                    }
                }
            };
            return controller;
        }

        // #69327 改變狀態為{0:加工 1:閒置}
        //20210604 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
        function changeMachineStatusProcess(content) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_EQP.edit_machine_state_process',
                content: content,
                success: function (data) {
                    //更改產線狀態後，重新取得產線狀態
                    lineStatusGet($scope.select_equipment_no_details);
                }
            });
        }

/****Dashboard**************************************************************************************************************************************/

        $scope.dashboardPanel = ['workLog','machineStatus','workOperator', 'workMaterial', 'productInfo', 'dashboard_info'];

        $scope.togglePanel = function(sectionName){
            var target = $scope.dashboard[sectionName];
            target.isContentHide = !target.isContentHide;
            if(sectionName == 'dashboard_info'){
                $scope.dashboard.dashboard_info.isForceHide = true;
            }
        };

        //今日生產任務- C隱藏，R置頂
        //20210605 modify by 德義林佳諺 for #0069327: 新增流水線暫停的功能( 類似離散的設備暫停機制 )
        var statusCount = 0;
        $scope.countStatus = function(item){
            // #0069327 計算R數量, 以決定閒置
            if (item.status == 'R')
                $scope.can_out_qty++;
            if (item.status == 'C')
                statusCount++;
        };

        $scope.goStatusR = function(){
            $timeout(function(){
                var workLogList = document.getElementsByClassName('kmi-list__workLog')[0];//angular.element(document).find('.workLog .kmi-list__row-content');
                workLogList.scrollTop = (+statusCount)*46+2;
                //console.log(workLogList.scrollTop);
            });
        };

         /***
         * 機台狀態列�?
         * 0:RUN(加工) - �?
         * 1:IDLE(閒置) - �?
         * 2:DOWN(故障) - �?
         * 3:SETUP(設置)
         * 4:SHUTDOWN(停機、關�?
         * 5:暫停(201609新增)
         * 6:維修(20190215新增)
         * 7:設置(20190215新增)
         **/
        $scope.machineStatus = function (status) {
            return 'status_'+status;
        };

        // 20220624 add by Alan for#100246 : 安灯生产线工作平台页面重制
        $scope.changeMachine = function(machine){
            $scope.machineItem = machine;
            andon_eqp_status_info_get(); // 取得安燈按鈕
            $scope.openToolBar('M');
        };

        $scope.getPlotInfo = function(plot, event){
            event.stopPropagation();
            $scope.plotItem = plot;
            lotinfo_get(plot, undefined, true);
        };

        $scope.getDefectReason = function(plot, type){
            var reasonList = [];
            var defect_reason = '';

            //首:0, 巡:1, 自:2, 末:3
            //20210525 modify by kaiinagami for M#84490: 自/首/巡/末, 4種檢的不良現象分開存放 
            if(type == '0'){
                reasonList = plot.first_check_defect_reason || [];
            }
            else if (type == '1') {
                reasonList = plot.inspect_defect_reason || [];
            }
            else if (type == '2') {
                reasonList = plot.self_defect_reason || [];
            }
            else if (type == '3') {
                reasonList = plot.end_defect_reason || [];
            }

            // reasonList = [{reason_no: '' ,reason_name:'破損'},{reason_no: '' ,reason_name:'不美觀'},{reason_no: '' ,reason_name:'粗糙'}];
            if(reasonList.length > 0){
                reasonList.forEach(function(reason){
                    if(defect_reason != ''){
                        defect_reason = defect_reason + '<br>';
                    }
                    defect_reason = defect_reason + reason.reason_name;
                });
            }
            return defect_reason;
        };

         /***
         * 生產批物料是否投�?
         * 20170425新增，is_materials= 0 顯示紅色�? 顯示綠色 �?1 不顯示顏�?
         * 20171113 mantis#0041868:調整，is_materials= 0 顯示紅色�? 顯示橘色�?綠色 �?1 不顯示顏�?
         */
        $scope.isMaterials = function(is_materials){
             switch (is_materials){
                 case '0':
                     return 'red';
                 case '1':
                     return 'yellow';
                 case '2':
                     return 'green';
             }
             return '';
        };
        /*Smt 生產�?開線狀�?*/
        $scope.isSmtState = function(is_smtstate)
        {
            switch (is_smtstate){
                case '1':
                    return 'yellow';
                case '2':
                    return 'green';
            }
            return '';
        };
        $scope.clickOperator = function(operator){
            if(!config.cache.permissions || config.cache.permissions.indexOf('B0203') != -1){
                var machineList = [
                    {machine_no :$scope.areaItem.area_no}
                ];
                $mdDialog.serviceDialog('B0203Service',machineList, operator, 'line', function(){
                    dog.bark();
                });
            } else {
                $scope.$root.showAlert($filter('translate')('common.msg.no_permissions'));
            }
        };

        // 20230224 modify by Alan for#: module_setting卡控
        $scope.changePanel = function(event, panelCode){
            event.stopPropagation();
            var panelList = [
                {panelCode : 'workMaterial', panelName: $filter('translate')('dashboard.workMaterial.title')},
                {panelCode : 'productInfo', panelName: $filter('translate')('dashboard.productInfo.title')},
                {panelCode : 'accessory', panelName: $filter('translate')('dashboard.accessory.title')}
            ];
            if($scope.feedingOpionOn){
                panelList.push({panelCode : 'workMaterialOp', panelName: $filter('translate')('dashboard.workMaterialOp.title')});
            }
            if($scope.ESI_CLD) {
                panelList.push({panelCode : 'countInfo', panelName: $filter('translate')('dashboard.countInfo.title')});
            }
            $scope.$root.showSelect({
                title : $filter('translate')('common.msg.plz_select'),
                label : 'panelName',
                code : 'panelCode',
                selectCode : panelCode,
                list : panelList,
                confirm : function(item, dialog){
                    var now_panel_index = $scope.dashboardPanel.indexOf(panelCode);
                    var select_panel_index = $scope.dashboardPanel.indexOf(item.panelCode);
                    //當為-1時表示選擇的不再列表內，則不用做交換
                    if(select_panel_index != -1){
                        $scope.dashboardPanel[select_panel_index] = panelCode;
                    }
                    $scope.dashboardPanel[now_panel_index] = item.panelCode;
                    if(item.panelCode == 'countInfo'){
                        localStorage.setItem(config.appName + '_B0201_panel', JSON.stringify($scope.dashboardPanel));
                    } else {
                        localStorage.removeItem(config.appName + '_B0201_panel', JSON.stringify($scope.dashboardPanel));
                    }
                   
                    dialog.hide();
                }
            });
        };

        //20210511 Modify by德義家興for#84772
        //當有生產批合併後會出現'+'號 點擊秀出由哪幾個生產批合併
        $scope.getWorkLogDetail = function(item,event){
            // event.stopPropagation();
            //準備資料;特定生產批的
            $scope.workLogTemp.splice(0,$scope.workLogTemp.length);
            $scope.workLogDetail.forEach(function(plot){
                //20220913 modify by wangzy for 0118716: 出站报工数据目前仅按照产品的生产批号进行合并，
                //没有作业站维度，需要增加，和表头的作业站没有关联关系
                if (plot.lotno == item.plot_no && plot.opno == item.op_no) {
                    $scope.workLogTemp.push(plot);
                }
            })
            openDialogWorkLogDetail(item); 
        }
        //'+'號開窗
        function openDialogWorkLogDetail(item){
            $mdDialog.dialog(
                'module/moduleB/program/B02/B0201/WorkLogDetail.tmp.html',
                function(dialog){
                    return{
                        plot_no: item.plot_no,
                        op_name: item.op_name,
                        op_no: item.op_no,
                        qty: item.qty,
                        workLogTemp: $scope.workLogTemp,
                        back: function () {
                            dialog.hide();
                        },
                        confirm:function(){
                            dialog.hide();
                        }
                    }
                }
            )
        }
        //取得每日生產任務;當日同一生產批出站的次數
        function getPlotV_CONTS(item,machine_no){
            $MMWService.pageNumberInfoGet({
                page_mode: 'getPlotV_CONTS',
                query_condition_info: [
                    { column_name: 'LOTNO', query_mode: '0', value: item.plot_no, merge_condition_model: 'AND' },
                    { column_name: 'OPNO', query_mode: '0', value: item.op_no, merge_condition_model: 'AND' },
                    { column_name: 'EQUIPMENTNO', query_mode: '0', value: machine_no, merge_condition_model: 'AND' }
                ]
            }, function (data) {
                    item.v_conts = data[0].v_conts;
            });
        }
        //取得每日生產任務;已出站生產批的資訊
        function getWorkLogPlotDetail(machine_no){
            $MMWService.pageNumberInfoGet({
                page_mode:'get_workLog_plot_detail',
                query_condition_info:[
                    { column_name: 'A.EquipmentNo', query_mode: '0', value: machine_no, merge_condition_model: 'AND' }
                ]
            }, function (data){
                $scope.workLogDetail = data;
            });
        }
/*****************************************************************************************************************/
        //barcode輸入
        $scope.input_plot_no = function(barcode){
            $scope.judge_mode(barcode);
        };

        $scope.judge_mode=function(barcode){
            if (barcode.split('ORD_001_')[0] === "") {
                // ORD_001_設備編號
                $scope.step_mode = 1;
                // 生產線無設備功能
            } else if (barcode == 'ORD_000_A001') {
                // ORD_000_A001 條碼上工
                $scope.step_mode = 2;
                $scope.ORD_directive = $filter('translate')('B0214.placeholder.step2');
            } else if (barcode == 'ORD_000_A002') {
                // ORD_000_A002 條碼下工
                $scope.step_mode = 3;
                $scope.ORD_directive = $filter('translate')('B0214.placeholder.step2');
            } else if (barcode == 'ORD_000_A003') {
                // ORD_000_A003 條碼進站
                $scope.step_mode = 4;
                $scope.plot_list=$scope.plot_list.filter(function(plotItem){
                    return plotItem.status === 'R';
                })
                $scope.ORD_directive = $filter('translate')('B0214.placeholder.step3');
            } else if (barcode == 'ORD_000_A004') {
                // ORD_000_A004 條碼出站
                $scope.step_mode = 5;
                $scope.plot_list=$scope.plot_list.filter(function(plotItem){
                    return plotItem.status === 'Q';
                })
                $scope.ORD_directive = $filter('translate')('B0214.placeholder.step3');
            } else if (barcode == 'ORD_000_A009') {
                $scope.step_mode = 0;
                $scope.ORD_directive ='';
            } else {
                $scope.next_step($scope.step_mode,barcode)
            }
        }

        $scope.next_step=function(mode,barcode){
            if(mode === 0){
                input_plot_no_callback(barcode);
            }else if(mode === 1){//設備功能
                // 生產線無設備功能
            }else if(mode === 2){//上工
                doWorkUpBarcode(barcode, 'U');
            }else if(mode === 3){//下工
                doWorkDownBarcode(barcode, 'D');
            }else if(mode === 4){//進站
                check_import_export_mode(mode,barcode);
            }else if(mode === 5){//出站
                check_import_export_mode(mode,barcode);
            }
        }

        //QRCode輸入
        $scope.qrcode_plot_no = function(){
            $scope.$root.OpenScanner({
                after : function(result){
                    $scope.judge_mode(result.text);
                },
                exception: function(){
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation : 'landscape'
            });
        };

        function input_plot_no_callback(barcode_plot_no){
            //檢查輸入的對不對
            var temp_plot_array = barcode_plot_no.split(';');
            $scope.dashboard['workLog'].barcode_plot_no = '';

            //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站-後端取得parameter數值(start)
            var plotItems = {'Q':[], 'R':[], 'W':[]};
            var content = {
                parameter_no: 'LotScanAutoCheckInOut'
            };
            $MMWService.sendToServer({
                uri:'ServicesSTD.Module_SYS.parameter_info_get',
                content: content,
                success: function(data){value = data.parameter_info_get_details[0].parameter_value;
                    if (data.parameter_info_get_details[0].parameter_value == 1){
                        $scope.dashboard['workLog'].production_info_detail.forEach(function(production_info){
                            if(temp_plot_array.length == 2){
                                // 20200327 modify by WeiTing for M#68073 - 生產線工作平台刷條碼應該是要刷入生產線而不是作業站。
                                if(barcode_plot_no == (production_info.plot_no + ';' + production_info.op_no)){
                                    if(!plotItems[production_info.status])
                                        plotItems[production_info.status] = [];
                                    plotItems[production_info.status].push(production_info);
                                }
                            } else {
                                if(barcode_plot_no == production_info.plot_no){
                                    if(!plotItems[production_info.status])
                                        plotItems[production_info.status] = [];
                                    plotItems[production_info.status].push(production_info);
                                }
                            }
            
                        });
                        // 20220222 modify by Alan for#10437: 修正掃碼找不到生產批對應邏輯
                            if(plotItems['R'].length == 0 && plotItems['Q'].length == 0 && plotItems['W'].length == 0){
                                if(temp_plot_array.length == 2){
                                    //刷入的生產批{{plot_no}}作業站{{op_no}}並不包含在今日生產任務內，請確定刷入的條碼與選擇的機台是否正確�?
                                    $scope.$root.showAlert($filter('translate')('B0214.msg.lotlog_opno_without_barcode', {plot_no:temp_plot_array[0], op_no:temp_plot_array[1]}));
                                } else {
                                    //刷入的生產批{{plot_no}}並不包含在今日生產任務內，請確定刷入的條碼與選擇的機台是否正確�?
                                    $scope.$root.showAlert($filter('translate')('B0214.msg.lotlog_without_barcode', {plot_no:temp_plot_array[0]}));
                                }
                            } else {
                                //20210524 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                if(plotItems['R'].length == 1 && plotItems['Q'].length == 1 && plotItems['W'].length == 0){
                                    // 20231030 modify by Alan for M#148761: 氣泡選單傳入多筆資料
                                    let plots = [];
                                    plots.push(plotItems['R'][0])
                                    plots.push(plotItems['Q'][0])
                                    $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {
                                        status:'B',
                                        plots: plots
                                    });
                                    //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                } else if(plotItems['Q'].length == 1 && plotItems['W'].length == 0 && plotItems['R'].length == 0){
                                    //只找到Q
                                    //直接進站
                                    $scope.plotItem = plotItems['Q'][0];
                                    var plotInfo = angular.merge({}, $scope.plotItem);
            
                                    // 20200731 modify by WeiTing for M#75817 - 修正在有派工數量的情況，條碼進站需判斷派工數量(dispatch_qty)和進站數量(qty)，哪個少就帶少的那個。
                                    plotInfo.dispatch_qty = plotInfo.dispatch_qty || 0;
                                    if(plotInfo.qty > plotInfo.dispatch_qty && plotInfo.dispatch_qty != 0){
                                        //派工數量少並且不為0則使用派工數量
                                        plotInfo.qty = plotInfo.dispatch_qty;
                                    }
                                    // //20210511 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                    // $mdDialog.serviceDialog('B0205Service', $scope.machineItem , $scope.plotItem, 'machine', function(){
                                    //     dog.bark();
                                    // });
                                    $scope.$root.getService('B0205Service', function($B0205Service){
                                        $B0205Service.SMES_PlotCheckInProcess({
                                            machine_no: $scope.areaItem.area_no,
                                            plotInfo : plotInfo,
                                            type: 'line',
                                            feedback : function(){
                                                dog.bark();
                                            }
                                        });
                                    });
                                    //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                } else if(plotItems['R'].length == 1 && plotItems['W'].length == 0 && plotItems['Q'].length == 0){
                                    //只找到R
                                    $scope.plotItem = plotItems['R'][0];
                                    var plotInfo = angular.merge({}, $scope.plotItem);
                                    //20221012 add by 翰鴻 for M#118366
                                    var proList = new Set();
                                    $.each($scope.dashboard.workLog.production_info_detail, function (index, obj) {
                                        if (obj.status == 'R' || obj.status == 'Q' || obj.status == 'W')
                                            proList.add(obj.item_no);
                                    });
                                    $scope.$root.getService('B0206Service', function($B0206Service){
                                        $B0206Service.init($scope.areaItem, plotInfo, 'line', 'B0201', function(){
                                            dog.bark();
                                        }, proList);
                                    });
                                } else {
                                    //'生產�?XXXX 狀態不為Q/R無法進站或出�?
                                    //$scope.$root.showAlert($filter('translate')('B0214.msg.cant_handle_barcode', {plot_no:temp_plot_array[1]}));
                                    $scope.workLogFilterShow.plot_no = true;
                                    $scope.workLogFilter.plot_no = temp_plot_array[0];
                                    //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站
                                    if (plotItems['Q'].length > 0) {
                                        $scope.plotItem = plotItems['Q'][0];
                                        $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {});
                                        //$scope.openToolBar(plotItems['Q'][(plotItems['Q'].length - 1)].status);
                                    } else if (plotItems['R'].length > 0) {
                                        $scope.plotItem = plotItems['R'][0];
                                        $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {});
                                        //$scope.openToolBar(plotItems['R'][(plotItems['R'].length - 1)].status);
                                    } else if (plotItems['W'].length > 0) {
                                        $scope.plotItem = plotItems['W'][0];
                                        $scope._event['production_info_detail'].openBubbleList($scope.plotItem, {});
                                        //$scope.openToolBar(plotItems['W'][(plotItems['W'].length - 1)].status);
                                    }
                                }
                            }
                    }else{
                        const $workLogScope = angular.element('.section.workLog').scope();   
                        $workLogScope._objproduction_info_detail.header[2].isFilter = true;
                        $workLogScope._objproduction_info_detail.filterColumns['plot_no'] = temp_plot_array[0];
                    }
                },
                error: function(e){
                    console.log('error_message', e);
                }
            });
            //20210412 modify by 德義_林佳諺 for #0086675 : 生產批條碼自動進出站-後端取得parameter數值(end)
        }

        $scope.openStatusFilter = function(){
            var statusList = [
                {display:$filter('translate')('dashboard.workLog.status.q'), code:'Q', isSelect:($scope.dashboard['workLog'].statusList.indexOf('Q')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.r'), code:'R', isSelect:($scope.dashboard['workLog'].statusList.indexOf('R')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.w'), code:'W', isSelect:($scope.dashboard['workLog'].statusList.indexOf('W')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.c'), code:'C', isSelect:($scope.dashboard['workLog'].statusList.indexOf('C')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.o'), code:'O', isSelect:($scope.dashboard['workLog'].statusList.indexOf('O')!=-1)},
                {display:$filter('translate')('dashboard.workLog.status.i'), code:'I', isSelect:($scope.dashboard['workLog'].statusList.indexOf('I')!=-1)}
            ];
            $scope.$root.showCheckList({
                label : 'display',
                code : 'code',
                order : '$index',
                list : statusList,
                confirm: function(checkList, dialog) {
                    var workLogstatusList = [];
                    statusList.forEach(function(status) {
                        if (status['isSelect']) {
                            workLogstatusList.push(status['code']);
                        }
                    })
                    if (workLogstatusList.length == 0) {
                        $scope.$root.showAlert($filter('translate')('common.abnormal_detail.msg.check_atLeast_one_condition'));
                    } else {
                        dialog.hide();
                        localStorage.setItem(config.appName + "_B0201_workLogStatusList", JSON.stringify(workLogstatusList));
                        $scope.dashboard['workLog'].statusList = [];
                        checkList.forEach(function(temp) {
                            if (temp.isSelect === true) {
                                $scope.dashboard['workLog'].statusList.push(temp.code);
                            }
                        });
                    }
                }
            });
        };

        $scope.favorite = function(callback){
            if(config.setting.OperatingArea==''){
                $scope.$root.showAlert($filter('translate')('home.showAlert'));
                return;
            }
            // 20230512 modify by chenshibo for#135176：我的最爱没有账号维护
            $mdDialog.serviceDialog('PasswordService', {
                mode: 'confirm',
                feedback: function () {
                    $MMWService.showQueryListPNIG({
                        page_mode: '0-1',
                        mode:'M',
                        key:'page_no',
                        header : [
                            {label: $filter('translate')('common.queryList.line_c'), code:'page_no'},
                            {label: $filter('translate')('common.queryList.line_n'), code:'page_name'}
                        ],
                        selectKey:{key:'favourite', true:'1', false:'0'},
                        setCondition:function(conditions){
                            conditions.push({column_name:'B.MASTERTYPE', query_mode:'0', value:'3', merge_condition_model:'AND' });
                            conditions.push({column_name:'B.MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                            return conditions;
                        },
                        confirm: function(selectItem, dialog){
                            var content = {
                                master_type: 3,
                                master_no :config.setting.OperatingArea,
                                favourite_line_detail:[]
                            };
                            if(selectItem && selectItem.length>0){
                                selectItem.forEach(function(item){
                                    if(item.favourite == '1'){
                                        content.favourite_line_detail.push({area_no:item.page_no});
                                    }
                                });
                            }
                            beforeSaveFavorite(content.favourite_line_detail, function(){
                                $MMWService.sendToServer({
                                    uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                                    content : content,
                                    success : function(data){
                                        dialog.hide();
                                        if(callback)
                                            callback();
                                    }
                                });
                            });
                        }
                    });
                }
            });
        };

        function beforeSaveFavorite(favoriteList, callback){
            var isDeleteCurrentOp = false;
            if($scope.areaItem.area_no && $scope.areaItem.area_no != ''){
                if(favoriteList && favoriteList.length > 0){
                    var filterList = $filter('filter')(favoriteList, {area_no: $scope.areaItem.area_no}, true);
                    if(filterList.length == 0){
                        isDeleteCurrentOp = true; //使用者將"目前的作業站"從我的最愛移除了
                    }
                }
            }

            if($scope.mode == 'list'){
                if(isDeleteCurrentOp){
                    //從我的最愛移除了目前的作業站，回到作業站選擇頁面
                    $scope.$root.showAlert($filter('translate')('B0201.msg.favorite_remove'),function(){
                        $scope.final(function(){
                            $scope.areaItem.area_no = '';
                            $scope.areaItem.areaName = '';
                            $scope.areaItem.areadisplay = '';
                            $scope.equipmentList = [];
                            $scope.machineItem = {};
                            $scope.mode = 'query';
                            if(callback)
                                callback();
                        });
                        config.selectItem = null; //我的最爱移除当前产线则将缓存也清除
                    });
                }else{
                    if(callback)
                        callback();
                }
            }else{
                if(isDeleteCurrentOp){
                    $scope.areaItem.area_no = '';
                    $scope.areaItem.areaName = '';
                    $scope.areaItem.areadisplay = '';
                }
                if(callback)
                    callback();
            }
        }

        //將排序物件轉成排序條件陣�?
        function genHeadOrderCondition(orderItem){
            var orderArray = [];
            var keys = Object.keys(orderItem);
            for(var i = 0; i<keys.length;i++){
                var key = keys[i];
                var prefix = (orderItem[key].order) ? '+' : '-';
                orderArray.push(prefix + key);
            }
            return orderArray;
        }

        $scope.clickHeadOrder = function(id){
            if(id == 'is_urgent'){
                if(!$scope.workLogOrder[id]){
                    $scope.workLogOrder = {
                        is_urgent : {order : false},
                        plot_no: {order: true},
                        op_no: {order: true}
                    }
                } else {
                    $scope.workLogOrder = {};
                }
            } else {
                if(!$scope.workLogOrder[id]){
                    // 尚未加入排序
                    $scope.workLogOrder[id] = {order: true};
                } else {
                    if($scope.workLogOrder[id].order){
                        // 若已正向排序 -> 改為反向排序
                        $scope.workLogOrder[id].order = false;
                    } else {
                        // 若已反向排序 -> 刪除此欄位的排序
                        delete $scope.workLogOrder[id];
                    }
                }
            }
        }

        /****************************以下為使用條碼刷入功能**************************************** */
        
        // B0202 上工 -- start
        // 條碼上工
        function doWorkUpBarcode(barcode, work_mode) {
            //上工是否需輸入原因
            $scope.need_work_up_reason = (config.cache.sys_parameter.EmployeeWorkReason=='1'||config.cache.sys_parameter.EmployeeWorkReason=='3'); 

            //20190705 modify by Dustdusk for M#59580: 將員工編號自動大寫
            barcode = barcode.toUpperCase();

            var content = {
                machine_no : $scope.areaItem.area_no,
                employee_no : barcode,
                report_datetime : new Date(),
                //return_type : '0'
                return_type : '10'
            };

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.user_information_get',
                content : content,
                success : function(data){
                    $scope.tmpOnWorkInfo = data;
                    $scope.tmpOnWorkInfo.shift_start_time = new Date();
                    if(config.setting.autoWorkset)
                        doWorkUp(work_mode);
                },
                error:function(data){
                    $scope.$root.showAlert(data.Message);
                }
            });
        }
        // 上工
        function doWorkUp(work_mode) {
            if(!$scope.tmpOnWorkInfo.employee_work_detail){
                $scope.$root.showAlert($filter('translate')('B0202.showAlert.column3'));
            } else {
                var msg = '';
                var confirm;
                if($scope.tmpOnWorkInfo.employee_work_detail.length!=0) {
                    for(var i=0; i<$scope.tmpOnWorkInfo.employee_work_detail.length; i++){
                        if($scope.areaItem.area_no == $scope.tmpOnWorkInfo.employee_work_detail[i].machine_no) {
                            msg = $filter('translate')('B0202.showAlert.column4');
                            confirm = function () {
                                $scope.tmpOnWorkInfo = {};
                            };
                            break;
                        }
                    }
                }

                if(msg == ''){
                    beforeEmpWorkUpSet(work_mode, function(){
                        empWorkUpSet(work_mode);
                    });
                } else {
                    $scope.$root.showAlert(msg, confirm);
                }
            }
        }
        // 檢查是否需要輸入上工原因
        function beforeEmpWorkUpSet(work_mode, callback) { 
            if($scope.need_work_up_reason && !$scope.tmpOnWorkInfo.reason_no){
                doWorkReasonDialog(work_mode, function(selectItem) {
                    $scope.tmpOnWorkInfo.reason_no = selectItem.page_no;
                    $scope.tmpOnWorkInfo.reason_name = selectItem.page_name;
                    if (callback)
                        callback();
                });
            } else {
                if (callback)
                    callback();
            }
        }
        //上工
        function empWorkUpSet(work_mode){
            var msg = '';
            var content = {
                employeewrokset:[]
            };

            msg += addWorkUpItem($scope.tmpOnWorkInfo, {machine_no :$scope.areaItem.area_no}, content.employeewrokset, work_mode);

            if(msg == ''){
                employee_wrok_up_set_Imp(content);
            } else {
                $scope.$root.showAlert(msg);
            }
        }
        function addWorkUpItem(tmpOnWorkInfo, machine, employeewrokset, work_mode){
            var msg = '';
            // if(type == 'machine'){
            //     //machineList.forEach(function(machine_detail){
            //         for(var i = 0; i < machine.employee_work_detail.length; i++){
            //             if(tmpOnWorkInfo.employee_no == machine.employee_work_detail[i].employee_no){
            //                 msg += $filter('translate')('B0202.msg.column1')+ machine.machine_no + $filter('translate')('B0202.msg.column2') +tmpOnWorkInfo.employee_no+ $filter('translate')('B0202.msg.column3')+ "<br>";
            //                 break;
            //             }
            //         }
            //     //});
            // }
            if($scope.need_work_up_reason && !tmpOnWorkInfo.reason_no){
                msg += $filter('translate')('B0202.showAlert.column5') + "<br>";
            }

            if(msg == ''){
                employeewrokset.push({
                    machine_no : machine.machine_no,
                    machine_name : machine.machine_name,
                    employee_no : tmpOnWorkInfo.employee_no,
                    work_mode : work_mode,
                    work_datetime : new Date(),
                    reason_no : tmpOnWorkInfo.reason_no || ''
                });
            }
            return msg;
        }
        function employee_wrok_up_set_Imp(content){
            var inspectInfo = {
                parent: 'B0201',
                op_no: '',
                area_no: '',
                user_no: $scope.tmpOnWorkInfo.employee_no,
                user_name: $scope.tmpOnWorkInfo.employee_name,
                user_title: $scope.tmpOnWorkInfo.user_title,
                releaser_verified: false,
                employeewrokset : angular.extend([], content.employeewrokset)
            };
            inspectUserSkill(inspectInfo, function(){
                employee_wrok_up_set(content);
            });
        }
        // 人員技能檢驗
        function inspectUserSkill(inspectInfo, feedback){
            if(inspectInfo.employeewrokset && inspectInfo.employeewrokset.length > 0){
                var machineInfo = inspectInfo.employeewrokset.shift();
                if(machineInfo.work_mode == 'U'){
                    $mdDialog.serviceDialog('B0231Service', {
                        parent: inspectInfo.parent,
                        machine_no: machineInfo.machine_no,
                        machine_name: machineInfo.machine_name,
                        position_no: machineInfo.position,
                        op_no: inspectInfo.op_no,
                        area_no: inspectInfo.area_no,
                        user_no: inspectInfo.user_no,
                        user_name: inspectInfo.user_name,
                        user_title: inspectInfo.user_title,
                        releaser_verified: inspectInfo.releaser_verified,
                        feedback: function(dialog){
                            if(dialog){
                                inspectInfo.releaser_verified = dialog.releaser_verified;
                                dialog.hide();
                            }
                            inspectUserSkill(inspectInfo, feedback);
                        }
                    });
                }else{
                    if(feedback)
                        feedback();
                }
            }else{
                if(feedback)
                    feedback();
            }
        }
        function employee_wrok_up_set(content){
            //20180518 modify by 李栋 for mantis#0047068
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                content : content,
                success : function(data){
                    $scope.$root.showToast($filter('translate')('B0202.showAlert.column1'));
                    //更新歷史下工紀錄
                    $scope.preOnWorkInfo = {};
                    $scope.preOnWorkInfo.employee_no = $scope.tmpOnWorkInfo.employee_no;
                    $scope.preOnWorkInfo.employee_name = $scope.tmpOnWorkInfo.employee_name;
                    $scope.preOnWorkInfo.work_time = $scope.tmpOnWorkInfo.shift_start_time;
                    $scope.tmpOnWorkInfo={};
                    $scope.tmpEmp_no = '';
                    dog.bark();
                    // try{
                    //     document.getElementById('tmpEmp_no').focus();
                    // } catch(e){console.error(e);}
                    // if(feedback)
                    //     feedback();
                }
            });
        }
        // B0202 上工 -- end

        // B0203 下工 -- start
        // 條碼下工
        function doWorkDownBarcode(barcode, work_mode) {
            //下工是否需輸入原因
            $scope.need_work_reason_down = (config.cache.sys_parameter.EmployeeWorkReason=='2'||config.cache.sys_parameter.EmployeeWorkReason=='3');

            //20190705 modify by Dustdusk for M#59580: 將員工編號自動大寫
            barcode = barcode.toUpperCase();

            var content = {
                machine_no : $scope.areaItem.area_no,
                employee_no : barcode,
                report_datetime : new Date(),
                //return_type : '0'
                return_type : '10'
            };

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SYS.user_information_get',
                content : content,
                success : function(data){
                    $scope.operator = data;
                    $scope.operator.shift_start_time = new Date();
                    if(config.setting.autoWorkset)
                        doWorkDown(work_mode);
                },
                error:function(data){
                    $scope.$root.showAlert(data.Message);
                }
            });
        }
        // 下工
        function doWorkDown(work_mode) {
            //是否有輸入下工人員
            if($scope.operator.employee_no && $scope.operator.employee_no!='') {
                if(!$scope.operator.employee_work_detail){
                    $scope.$root.showAlert($filter('translate')('B0203.showAlert.column2'));
                    // document.getElementById('employee_no').focus();
                } else {
                    //20170602 modify by Dustdusk for 作業區也需要檢核是否下工過
                    //if(type=='line'){
                        //為生產線
                        var msg = '';
                        var confirm;
                        if(!checkOutWork($scope.areaItem.area_no, $scope.operator.employee_work_detail)){
                            msg = $filter('translate')('B0203.showAlert.column3');
                            confirm = function () {
                                $scope.operator = {employee_no:'', reason_no: ''};
                            };
                        }

                        if(msg == ''){
                            beforeEmpWorkDownSet(work_mode, function(){
                                empWorkDownSet(work_mode);
                            });
                        } else {
                            $scope.$root.showAlert(msg, confirm);
                        }
                    // } else {
                    //     //為作業區
                    //     empWorkSet(dialog);
                    // }
                }
            }else{
                $scope.$root.showAlert($filter('translate')('B0203.showAlert.column1'));
                document.getElementById('employee_no').focus();
            }
        }
        //上工檢核
        //回傳true表示該員工有在此機台上工
        function checkOutWork(machine_no, employee_work_detail){
            var isOnWork;
            for(var i=0; i< employee_work_detail.length; i++){
                if(machine_no == employee_work_detail[i].machine_no) {
                    isOnWork = true;
                    break;
                }else{
                    isOnWork = false;
                }
            }
            return isOnWork;
        }
        function beforeEmpWorkDownSet(work_mode, callback){
            if($scope.need_work_reason_down && !$scope.operator.reason_no){
                doWorkReasonDialog(work_mode, function(selectItem) {
                    $scope.operator.reason_no = selectItem.page_no;
                    $scope.operator.reason_name = selectItem.page_name;
                    if (callback)
                        callback();
                });
            } else {
                if (callback)
                    callback();
            }
        }
        function empWorkDownSet(work_mode) {
            var msg = '';
            var content = {
                employeewrokset:[]
            };

            // machineList.forEach(function(machine){
                msg += addWorkDownItem($scope.operator, {machine_no :$scope.areaItem.area_no}, content.employeewrokset, work_mode);
            // });

            if(msg == ''){
                //20180518 modify by 李栋 for mantis#0047068
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SYS.employee_wrok_set_process',
                    content : content,
                    success : function(data){
                        $scope.$root.showToast($filter('translate')('B0203.showAlert.column4'));
                        $scope.preOffWorkInfo = angular.extend({}, $scope.operator);
                        $scope.operator = {employee_no:'', reason_no: ''};
                        dog.bark();
                        // try{
                        //     document.getElementById('employee_no').focus();
                        // } catch(e){console.error(e);}
                        // if(feedback)
                        //     feedback();
                    }
                });
            } else {
                $scope.$root.showAlert(msg);
            }
        }
        function addWorkDownItem(operator, machine, employeewrokset, work_mode){
            var msg = '';
            // if(type == 'machine'){
            //     //machineList.forEach(function(machine_detail){
            //         var isOnWork = false;
            //         for(var i = 0; i < machine.employee_work_detail.length; i++){
            //             if(operator.employee_no == machine.employee_work_detail[i].employee_no){
            //                 isOnWork = true;
            //                 break;
            //             }
            //         }
            //         if(!isOnWork){
            //             msg += $filter('translate')('B0203.msg.column1') + machine.machine_no + $filter('translate')('B0203.msg.column2') +operator.employee_no+ $filter('translate')('B0203.msg.column3') + '<br>';
            //         }
            //     //});
            // }

            if($scope.need_work_reason_down && !operator.reason_no){
                msg += $filter('translate')('B0203.showAlert.column5') + "<br>";
            }

            if(msg == ''){
                employeewrokset.push({
                    machine_no : machine.machine_no,
                    employee_no : operator.employee_no,
                    work_mode : work_mode,
                    work_datetime : new Date(),
                    reason_no : operator.reason_no || ''
                });
            }
            return msg;
        }
        // B0203 下工 -- end

        // 上下工共用方法 -- start
        // 條碼輸入上下工原因開窗
        function doWorkReasonDialog(work_mode, callback) {
            var title = '';

            if(work_mode == 'U') { //上工 (U)
                title = $filter('translate')('B0214.plz_select_online_reason');
            } else { // 下工 (D)
                title = $filter('translate')('B0214.plz_select_offline_reason');
            }

            $timeout(function() {
                if(document.activeElement.tagName != 'INPUT') {
                    document.getElementById("doWorkReason").focus();
                }
            });

            $mdDialog.dialog(
                'module/moduleB/program/barcode/doWorkReason.tmp.html',
                function (dialog) {
                    return {
                        title: title,
                        doWorkReason: '',
                        back: function() {
                            dialog.hide();
                        },
                        input_do_work_reason: function(event) {
                            if(event.keyCode === 13) {
                                dialog.input_do_work_reason_callback();
                            }
                        },
                        qrcode_do_work_reason: function() {
                            $scope.$root.OpenScanner({
                                after : function(result){
                                    dialog.input_do_work_reason_callback(result.text);
                                },
                                exception: function(){
                                    //目前裝置無法使用相機
                                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                                },
                                orientation : 'landscape'
                            });
                        },
                        input_do_work_reason_callback: function() {
                            if (dialog.doWorkReason === 'ORD_000_A009'){
                                // ORD_000_A009 關閉按鈕
                                dialog.hide();
                            } else {
                                loadEmpWorkReasonBarcode(work_mode, dialog.doWorkReason, dialog, function(doWorkReason){
                                    dialog.hide();
                                    if(callback)
                                        callback(doWorkReason);
                                });
                            }
                        }
                    }
                }
            );
        }
        // 判斷刷入的上下工原因是否存在
        function loadEmpWorkReasonBarcode(work_mode, barcode, dialog, callback){
            var query_condition_info = [{column_name:'ISSUESTATE', query_mode:'0', value:'2', merge_condition_model:'AND'}];

            if(work_mode == 'D'){ // 下工
                query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'1', merge_condition_model:'AND' });
            } else if(work_mode == 'U'){ //上工
                query_condition_info.push({column_name:'REASONTYPE', query_mode:'0', value:'0', merge_condition_model:'AND' });
            }

            $MMWService.pageNumberInfoGet({
                page_mode : '35',
                query_condition_info: query_condition_info
            }, function(items){
                if(items && items.length > 0){
                    var isReasonMatch = false;
                    for (var i = 0; i < items.length; i++) {
                        if(items[i].page_no === barcode) {
                            isReasonMatch = true;
                            if(callback)
                                callback(items[i]);
                            break;
                        }
                    }
                    if(!isReasonMatch) {
                        dialog.doWorkReason = '';
                        if (work_mode == 'D') { // 下工
                            // 查無此上工原因
                            $scope.$root.showAlert($filter('translate')('B0214.barcode_msg.column3'));
                        } else if(work_mode == 'U'){ //上工
                            // 查無此下工原因
                            $scope.$root.showAlert($filter('translate')('B0214.barcode_msg.column2'));
                        } 
                    }
                } else {
                    dialog.doWorkReason = '';
                    if(work_mode == 'D'){ // 下工
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column8'));
                    } else if(work_mode == 'U'){ //上工
                        $scope.$root.showAlert($filter('translate')('B0214.showAlert.column7'));
                    }
                }
            });
        }
        // 上下工共用方法 -- end

        //進出站開窗 add by Oliver for M#73832
        function open_export_outport_dialog(mode_num,plot_status,barcode){//進出站開窗
            $scope.plot_list=$scope.plot_list.filter(function(plotItem){
                return plotItem.status === plot_status;
            })
            let check_plot=false;
            $scope.plot_list.forEach(function(item){
                if(item.plot_no = barcode){
                    check_plot=true;
                    $scope.plotItem = item;
                    $scope.plotItem.open_scan_column=true;
                };
            });

            if(!check_plot){
                $scope.$root.showAlert($filter('translate')('B0214.showAlert.column9'));
                return
            }
            dialogList[mode_num].init(plot_status);
        }

        //檢查進出站mode add by Oliver for M#73832
        function check_import_export_mode(mode_num,barcode){
            if(mode_num===4){//進站
                if(dialogList[mode_num].programName==='B0205'){
                    open_export_outport_dialog(mode_num,'Q',barcode);
                }else{
                    let import_mode;
                    dialogList.forEach(function(item,key){
                        if(item.programName==='B0205'){
                            import_mode=key;
                        }
                    });
                    open_export_outport_dialog(import_mode,'Q',barcode);
                }
            }else if(mode_num===5){//出站
                if(dialogList[mode_num].programName==='B0206'){
                    open_export_outport_dialog(mode_num,'R',barcode);
                }else{
                    let export_mode;
                    dialogList.forEach(function(item,key){
                        if(item.programName==='B0206'){
                            export_mode=key;
                        }
                    });
                    open_export_outport_dialog(export_mode,'R',barcode);
                }
            }
        }

        // 20211101 modify by Alan for #93040 : [成綸企業][優化]sMES整合QMS卡控出站檢，拋檢驗單時於生產任務面板增加檢驗單號及推送時間欄位
        // 增加送驗時間欄位排序功能
        $scope.reverse = false;
        $scope.orderColumn = '';
        $scope.OrderChange = function (columnName) {
            if ($scope.orderColumn == columnName) {
                $scope.reverse = !$scope.reverse;
            } else {
                $scope.orderColumn = columnName;
                $scope.reverse = false;
            }
        };

        // 20220624 add by Alan for#100246 : 安灯生产线工作平台页面重制
        const isEmpty = (obj) => Object.keys(obj).length === 0;
    }
];});
